<?php

/**
 * 密友圈个人主页相关
 */
class quan
{
    public function checkMUserAuth($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $qId = $param->qId;
        $uid = Session::$user['uid'];
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $result = $quanModel->where($where)->find();
        Session::switchCustomer($customerId);
        if ($result) {
            if ($result["deleted"] == 1) { //密友已经停用
                $location = C("SERVER_HOST") . "call.html?customerId=$customerId&module=quan&method=auth";
                redirect($location);
                return;
            }
        }
        return;
    }

    public function getIndex($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//		self::checkMUserAuth($param);
        $IsBind = self::checkBind($param);
        if ($IsBind["status"] && !$param) {
            $location = $IsBind["location"];
            redirect($location);
            return;
        }
        if ($param) {
            $qId = $param->qId;
        } else {
            $qId = $IsBind["qId"];
        }
        $uid = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        $weixinUserModel = M("user_weixin_info");
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $result = $quanModel->where($where)->find();
        if (!$result) {
            Output::instance()->resultCode(1, "无权限访问");
            return;
        }
        Session::switchCustomer($customerId);
        if ($result) {
            $userList = $userModel->where("id=$uid")->find();
            if ($userList && $userList["phone"] != "") { //判断是否注册过，根据手机号判断
                $result["subscribe"] = 1;
            } else {
                $result["subscribe"] = 0;
            }
            if (!$result["isAddRecomment"]) { //没有同步过，则同步默认素材
                self::addDefaultRecomment($param);
            }
        }
        $result["qId"] = $qId;
        $param->page = "shopIndex";
        $sId = self::addShare($param);
        //添加分享相关
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
            $result["isShare"] = 1;
        }
        $result["sId"] = $sId;
        $result["fromUId"] = $uid;
        //读取数据
        Output::instance()->module('quan', "index")->object($result);
    }

    /**
     * [getIndexData 获取首页数据]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function getIndexData($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uId = Session::$user['userId'];
        $qId = $param->qId;
        if ($fromUId) {
            $uId = $fromUId;
        }
        $miShareModel = M("mishare");
        $order = "a.createTime desc";
        $start = $param->start;
        $limit = $param->limit;
        $pageStart = $start * $limit;
        $where["a.deleted"] = array('eq', 0);
        $where["a.module"] = array(
            array('eq', 'product'),
            array('eq', "micontent"),
            array('eq', "shenqi"),
            'or'
        );
        $proList = $miShareModel->alias("a")
            ->join("inner join wx_mishare_material b on b.sId =a.id")
            ->field("a.id,a.module,a.moduleId,b.description,a.createTime,b.title")
            ->where($where)
            ->order($order)
            ->limit($pageStart, $limit)
            ->select();

        foreach ($proList as $key => $value) {
            $proList[$key]["date"] = format_date(strtotime($value["createTime"]));
            $p = new StdClass();
            $p->miUId = $uId;
            $p->qId = $qId;
            $p->id = $value["moduleId"];
            $detail = Module::callModule($value["module"], Session::$user, "getObjectDetail", $p);
            $proList[$key]["detailUrl"] = $detail["detailUrl"];
        }
        $count = $miShareModel->alias("a")
            ->join("inner join wx_mishare_material b on b.sId =a.id")
            ->where($where)
            ->order($order)
            ->count();

        $result["proList"] = $proList;
        $result["count"] = $count;
        $result["pageCount"] = getPageCount($count, $limit);
        Output::instance()->object($result);
    }

    /**
     * 密友圈主页
     */
    public function userIndex($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//		self::checkMUserAuth($param);
        $qId = $param->qId;
        $uid = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        if($customerId == 96){
            cookie("openid_$customerId", null);
            cookie("userId_$customerId", null);
            Log::write('jie----quan-'.$uid.'-'.$userName);
        }
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $miquanModel = M("miyouquan");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $where["deleted"] = array('eq', 0);
        $result = $quanModel->where($where)->find();
        $quanInfo = $miquanModel->where("id=$qId")->find();
        $userList = $userModel->where("id=$uid")->find();
        if (!$result && $qId) {
            //此时用户不在这个圈里面
            $joinresult = $quanModel->alias("a")
                ->join("inner join wx_miyouquan b on a.qid = b.id")
                ->where("a.uid=$uid and b.cId=$customerId and a.deleted=0 and a.status=1 and a.qid<>$qId")
                ->find();
            if ($joinresult) {
                Output::instance()->resultCode(1, '已存在另外一个圈中');
                return;
            }
            //开启了自动加入
            if ($quanInfo['staffJoin']) {
                $cusWhere["agent"] = array("eq", "service");
                $cusWhere["customerId"] = array("eq", $customerId);
                $cusWhere["openid"] = array("eq", $userName);
                $staffInfo = $customerUser->where($cusWhere)->find();
                if ($staffInfo) {
                    $quaParams = new stdClass();
                    $quaParams->userName = $userName;
                    //$quaParams->miUId = $param->miUId;
                    $quaParams->id = $qId;
                    $quanInfo['signSaleSource'] ? $quaParams->signSaleSource = 1 : "";
                    self::subscribeRegQuanUser($quaParams);
                }
            }
            if ($quanInfo["registerStatus"] == 1) {
                if ($quanInfo["joinContent"]) {
                    $miInfo = $miquanModel->alias("a")
                        ->join("inner join wx_module_product b on a.joinPid=b.id")
                        ->field("b.fromCustomerId")
                        ->where("a.id=$qId")->find();
                    if ($miInfo) {
                        $location = C("SERVER_HOST") . "call.html?customerId=" . $miInfo['fromCustomerId'] . "&module=quan&method=payContent&params=" . urlencode(json_encode($param));
                        redirect($location);
                        return;
                    } else {
                        self::payContent($param);
                    }
                    return;
                }
                self::getMiregPage($param);
                return;
            } else if ($quanInfo["joinType"] == 1) {
                $quaParams = new stdClass();
                $quaParams->userName = $userName;
                $quaParams->id = $qId;
                $quaParams->miUId = $param->miUId;
                self::subscribeRegQuanUser($quaParams);
                $param->examine = 1;
                self::getMiregPage($param);
                return;
            } else {
                $quaParams = new stdClass();
                $quaParams->userName = $userName;
                $quaParams->id = $qId;
                $quaParams->miUId = $param->miUId;
                self::subscribeRegQuanUser($quaParams);
            }
        } else if ($qId && !$result["status"]) {
            $param->examine = 1;
            self::getMiregPage($param);
            return;
        }

        $condition["a.qid"] = array('eq', $qId);
        $condition["a.uid"] = array('eq', $uid);
        $result = $quanModel->alias("a")
            ->join("inner join wx_miyouquan b on a.qid=b.id")
            ->where($condition)->find();
        $result["qId"] = $qId;
        $param->page = "shopIndex";
        $sId = self::addShare($param);
        //添加分享相关
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
            $result["isShare"] = 1;
        }
        $result["sId"] = $sId;
        $result["fromUId"] = $uid;
        $community = $param->community;
        if ($community) {
            $params = new StdClass();
            $params->qid = $qId;
            Module::callModule("community", NULL, 'index', $params);
        } else {
            Output::instance()->module('quan', "quanUserIndex")->object($result);
        }
    }

    //购买介绍页面
    public function payContent($param)
    {
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $MiQuanModel = M("miyouquan");
        $mimall = M("mimall_user");
        Session::switchCustomer($customerId);
        if (!$param->miUId) {
            $miInfo = $MiQuanModel->alias("a")
                ->join("inner join wx_module_product b on a.joinPid=b.id")
                ->field("b.fromCustomerId")
                ->where("a.id=$qId")->find();
            if ($miInfo) {
                $mimallwhere["qId"] = array('eq', $qId);
                $mimallwhere["uId"] = array('eq', $uid);
                $mimallwhere['cId'] = array("eq", $miInfo['fromCustomerId']);
                $mallResult = $mimall->where($mimallwhere)->find();
                if (!$mallResult) {
                    $param->qId = $qId;
                    $param->miUId = $uid;
                    $location = C("SERVER_HOST") . "call.html?customerId=" . $miInfo['fromCustomerId'] . "&module=quan&method=payContent&params=" . urlencode(json_encode($param));
                    redirect($location);
                    return;
                }
            }
        }
        $miInfo = $MiQuanModel->where("id=$qId")->find();
        if ($miInfo["joinContent"]) {
            $miInfo["joinContent"] = json_decode($miInfo["joinContent"], true);
        }
        if (self::joinQualifications($qId)) {
            $miInfo['satisfy'] = 1;
        } else {
            $miInfo['satisfy'] = 0;
        }
        $miInfo["qId"] = $qId;
        $miInfo["miUId"] = $param->miUId;
        $planCustomerId = C("PLANT_CUSTOMERID");
        $miInfo['planCustomerId'] = $planCustomerId;
        Output::instance()->module("quan", "payContent")->object($miInfo);
    }

    /**
     * 同步默认推荐到每个用户
     */
    public function addDefaultRecomment($param)
    {
        $uid = Session::$user['uid'];
        $qId = $param->qId;
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $recommentModel = M("mirecomment");
//        $venderModel = M("quan_vendor");
        $miYouQuanModel = M("miyouquan");
        $quanUserModel = M("quan_user");
        Session::switchCustomer($customerId);
        $miContentList = $miYouQuanModel->alias("a")
            ->join("inner join wx_micontent b on a.vid=b.vId")
            ->join("inner join wx_mishare c on b.id=c.moduleId")
            ->join("inner join wx_mishare_material d on d.sId =c.id")
            ->field("c.id,d.title,d.shareImg,d.shareImg1,d.description")
            ->where("b.isRecommend=1 and b.deleted=0 and c.module='micontent' and a.id=$qId")->select();

        if ($miContentList) {
            foreach ($miContentList as $key => $value) {
                $sId = $value["id"];
                $addData = array(
                    "uId" => $uid,
                    "quanId" => $qId,
                    "sId" => $sId,
                    "createTime" => date("Y-m-d H:i:s"),
                    "deleted" => 0
                );
                $rs = $recommentModel->where("uId='$uid' and quanId='$qId' and sId='$sId'")->find();
                if (!$rs || count($rs) < 1) { //防止重复插入
                    $recommentModel->add($addData);
                }
            }
            //更新添加标志
            $upWhere["qid"] = array('eq', $qId);
            $upWhere["uid"] = array('eq', $uid);
            $upData["isAddRecomment"] = 1;
            $quanUserModel->where($upWhere)->save($upData);
        }
    }

    /**
     * [addShare 通用添加mishare记录]
     * @param [type] $module   [description]
     * @param [type] $moduleId [description]
     */
    public function addShare($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $result = $quanModel->alias("a")
            ->join("inner join wx_miyouquan b on b.id=a.qid")
            ->field("a.*,b.logo,b.name as qName")
            ->where($where)->find();
        if ($result) {
            //添加到分享列表
            $module = $param->page;
            $moduleId = $result["id"];
            $miShareModel = M("mishare");
            $miShareMaterModel = M("mishare_material");
            $result = $miShareModel->where("module='$module' and moduleId=$moduleId")->find();

            if (!$result || count($result) <= 0) {
                $miShareModel->startTrans();
                $addData = array(
                    "module" => $module,
                    "moduleId" => $moduleId,
                    "shareCount" => 0,
                    "viewCount" => 0,
                    "viewUv" => 0,
                    "shareUv" => 0,
                    "praiseCount" => 0,
                    "commentCount" => 0,
                    "createTime" => date('Y-m-d H:i:s'),
                    "delete" => 0,
                    "tplId" => 0
                );
                $sId = $miShareModel->add($addData);
                $userInfo = self::getUserInfo($param);
                if (!$sId) {
                    $miShareModel->rollback();
                    return;
                }
                $addMeterData = array(
                    "sId" => $sId,
                    "title" => $result["nickname"] . "的密友圈",
                    "shareImg" => $userInfo->headImgUrl,
                    "description" => $result["slogan"]
                );
                $success = $miShareMaterModel->add($addMeterData);
                if ($success) {
                    $miShareModel->commit();
                }

            } else {
                $sId = $result["id"];
            }
        }
        $result["sId"] = $sId;
        Session::switchCustomer($customerId);
        return $sId;
    }

    /**
     * [home 个人资料]
     * @return [type] [description]
     */
    public function home($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $result = $quanModel->where($where)->find();
        $result["qId"] = $qId;
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $result["fromUId"] = $uid;
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "account")->object($result);
    }

    public function getUserInfo($param)
    {
        $uid = Session::$user['userId'];
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $qId = $param->qId;
        $quanModel = M("quan_user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $result = $quanModel->alias("a")
            ->join("inner join wx_miyouquan b on b.id=a.qid")
            ->field("a.*,b.logo,b.name as qName")
            ->where($where)->find();
        return $result;
    }

    public function shopIndex($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        Session::switchCustomer(0);
        $result = self::getUserInfo($param);

        if ($result) {
            $result["qId"] = $qId;
            //添加到分享列表
            $param->page = "shopIndex";
            $sId = self::addShare($param);
            $Guid = new Guid();
//			$guid = $Guid->toString();//分享用的id			-----Lp
            //获取分享具体内容
            $param->sId = $sId;

            //添加一次浏览记录
            $result["sId"] = $sId;
            $visitParam = new StdClass();
//			$visitParam->guid=$guid;						-----Lp
            $visitParam->sId = $sId;
            $visitParam->fromPage = "shopIndex";
            $visitParam->fromGuid = $param->fromGuid;
            $visitParam->miUId = $param->miUId;

            $visitid = self::addVisit($visitParam);
//			$result["guid"]=$guid;							-----Lp
            $result["miUid"] = $uid;
            $result["miUTime"] = date('Y-m-d H:i:s');
            $result["visitid"] = $visitid;
            $result["sId"] = $sId;
            if ($fromUId) {
                $result["fromUId"] = $fromUId;
                $result["isShare"] = 1;
            } else {
                $result["fromUId"] = $uid;
            }
        }
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "shopIndex")->object($result);
    }

    /**
     * [shopStart 店铺初始化引导页面] //未处理 -LP
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function shopStart($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['uid'];
        $qId = $param->qId;
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        Session::switchCustomer(0);
        $result = self::getUserInfo($param);
        if ($result) {
            $result["qId"] = $qId;
            //添加到分享列表
            $param->page = "shopStart";
            $sId = self::addShare($param);
            $Guid = new Guid();
            $guid = $Guid->toString();//分享用的id
            //获取分享具体内容
            $param->sId = $sId;

            //添加一次浏览记录
            $result["sId"] = $sId;
            $visitParam = new StdClass();
            $visitParam->guid = $guid;
            $visitParam->sId = $sId;
            $visitParam->fromPage = "shopStart";
            $visitParam->fromGuid = $param->fromGuid;
            $visitParam->miUId = $param->miUId;

            $visitid = self::addVisit($visitParam);
            $result["guid"] = $guid;
            $result["visitid"] = $visitid;
            $result["sId"] = $sId;
            if ($fromUId) {
                $result["fromUId"] = $fromUId;
                $result["isShare"] = 1;
            } else {
                $result["fromUId"] = $uid;
            }
        }
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "shopStart")->object($result);
    }

    public function getShopStartList($qId, $start = 0, $limit = 10, $fromUId = "")
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uId = Session::$user['uid'];
        if ($fromUId) {
            $uId = $fromUId;
        }
        $miRecommentModel = M("mirecomment");
        $order = "a.createTime desc";
        $pageStart = $start * $limit;
        $where["a.deleted"] = array('eq', 0);
        $where["a.uId"] = array('eq', $uId);
        $where["b.module"] = array(
            array('eq', 'product'),
            array('eq', "micontent"),
            array('eq', "shenqi"),
            'or'
        );
        $proList = $miRecommentModel->alias("a")
            ->join("inner join wx_mishare b on a.sId=b.id")
            ->join("inner join wx_mishare_material c on c.sId =b.id")
            ->field("b.module,b.moduleId,a.createTime,a.id,c.title,c.shareImg,c.shareImg1,c.description")
            ->where($where)
            ->order($order)
            ->limit($pageStart, $limit)
            ->select();

        foreach ($proList as $key => $value) {
            $proList[$key]["date"] = format_date(strtotime($value["createTime"]));
            $p = new StdClass();
            $p->miUId = $uId;
            $p->qId = $qId;
            $p->id = $value["moduleId"];
            $detail = Module::callModule($value["module"], Session::$user, "getObjectDetail", $p);
            $proList[$key]["detailUrl"] = $detail["detailUrl"];
        }
        $count = $miRecommentModel->alias("a")
            ->join("inner join wx_mishare b on a.sId=b.id")
            ->join("inner join wx_mishare_material c on c.sId =b.id")
            ->where($where)
            ->order($order)
            ->count();

        $result["qId"] = $qId;
        $result["proList"] = $proList;
        $result["count"] = $count;
        $result["pageCount"] = getPageCount($count, $limit);
        Session::switchCustomer($customerId);
        Output::instance()->object($result);
    }

    /**
     * [getShopPro 密友商品主页]
     * @param  [type]  $qId   [description]
     * @param  integer $start [description]
     * @param  integer $limit [description]
     * @return [type]         [description]
     */
    public function getShopPro($qId, $start = 0, $limit = 10, $fromUId = "")
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uId = Session::$user['uid'];
        if ($fromUId) {
            $uId = $fromUId;
        }
//        $vendorModel = M("quan_vendor");
        $miYouQuanModel = M("miyouquan");
        $order = "b.createTime desc";
        $pageStart = $start * $limit;
        $where["a.id"] = array('eq', $qId);
        $where["b.isRemoved"] = array('eq', 0);
        $where["b.deleted"] = array('eq', 0);
        $where["a.deleted"] = array('eq', 0);
        $where["b.ordinary"] = array('eq', 1);
        $proList = $miYouQuanModel->alias("a")
            ->join("inner join wx_module_product b on a.vid=b.vId")
//            ->join("INNER JOIN wx_miyouquan c ON c.id=a.quanId")
            ->join("INNER JOIN (SELECT * FROM wx_mishare WHERE module='product') AS d ON d.moduleId=b.id ")
            ->field("b.id as id,b.id as pId,b.name,b.fromCustomerId,b.picUrl,b.fixedPrice,b.discountedPrice,b.salesCount,b.saleCut,b.tplId,ROUND(b.saleCut*a.miAward,2) AS miAward,d.id as sId")
            ->where($where)
            ->order($order)
            ->limit($pageStart, $limit)
            ->select();

        $count = $miYouQuanModel->alias("a")
            ->join("inner join wx_module_product b on a.vid=b.vId")
//            ->join("INNER JOIN wx_miyouquan c ON c.id=a.quanId")
            ->join("INNER JOIN (SELECT * FROM wx_mishare WHERE module='product') AS d ON d.moduleId=b.id ")
            ->where($where)
            ->order($order)
            ->count();

        $result["qId"] = $qId;
        $result["proList"] = $proList;
        $result["count"] = $count;
        $result["pageCount"] = getPageCount($count, $limit);
        Session::switchCustomer($customerId);
        Output::instance()->object($result);
    }

    public function saveUser($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $data = array(
            "nickName" => $param->nickName,
            "headImgUrl" => $param->headImgUrl,
            "wxId" => $param->wxId,
            "thefeImgUrl" => $param->themeImgUrl,
            "slogan" => $param->slogan
        );
        Session::switchCustomer($customerId);
        $result = $quanModel->where($where)->save($data);
        if ($result !== false) {
            Output::instance()->resultCode(code_success);
        }
    }

    /**
     * [index_pro 密友商品列表]
     * @param  [type] $qId [description]
     * @return [type]      [description]
     */
    public function index_pro($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uid = Session::$user['uid'];
        $qId = $param->qId;
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $result = self::getUserInfo($param);
        $result["qId"] = $qId;
        $result["sId"] = $sId;
        $result["fromUId"] = $uid;
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "quan_product")->object($result);
    }

    public function miu_pro($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uid = Session::$user['uid'];
        $qId = $param->qId;
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $result = self::getUserInfo($param);
        $result["qId"] = $qId;
        $result["sId"] = $sId;
        $result["fromUId"] = $uid;
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "quan_mproduct")->object($result);
    }


    /**
     * [getProList 获取分类商品信息]
     * @param  [type]  $qId   [description]
     * @param  integer $type [description]
     * @param  integer $start [description]
     * @param  integer $limit [description]
     * @return [type]         [description]
     */
    public function getProList($qId, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $protype = 'ordinary';
        $proList = self::getProductByType($qId, $start, $limit);
        $result["qId"] = $qId;
        $result["proList"] = $proList;
        Session::switchCustomer($customerId);
        Output::instance()->object($result);
    }

    /**
     * [getMiuProList 获取密友特供分类商品信息]
     * @param  [type]  $qId   [description]
     * @param  integer $type [description]
     * @return [type]         [description]
     */
    public function getMiuProList($qId, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $protype = 'specialpro';
        $proList = self::getProductByType($qId, $start, $limit, $protype);
        $result["qId"] = $qId;
        $result["proList"] = $proList;
        Session::switchCustomer($customerId);
        Output::instance()->object($result);
    }

    /**
     * [getProductByType 按商品加入销量或者时间排序返回]
     * @param  [type] $qId   [description]
     * @param  [type] $type  [description]
     * @param  [type] $start [description]
     * @param  [type] $limit [description]
     * @return [type]        [description]
     */
    public function getProductByType($qId, $start, $limit, $protype = 'ordinary')
    {
        $uId = Session::$user['uid'];
//        $vendorModel = M("quan_vendor");
        $miYouQuanModel = M("miyouquan");
        $order = "b.salesCount desc";
        $pageStart = $start * $limit;
        $where["a.id"] = array('eq', $qId);
        $where["b.isRemoved"] = array('eq', 0);
        $where["b.deleted"] = array('eq', 0);
        $where["a.deleted"] = array('eq', 0);

        $result = $miYouQuanModel->alias("a")
            ->join("inner join wx_module_product b on a.vid=b.vId")
//            ->join("INNER JOIN wx_miyouquan c ON c.id=a.quanId")
            ->join("INNER JOIN (SELECT * FROM wx_mishare WHERE module='product') AS d ON d.moduleId=b.id ")
            ->join("LEFT JOIN (SELECT sId as msId,deleted  FROM wx_mirecomment WHERE uId=$uId AND quanId=$qId and deleted=0 ) com ON com.msId=d.id ")
            ->field("b.id as id,b.id as pId,b.name,b.fromCustomerId,b.picUrl,b.fixedPrice,b.discountedPrice,b.salesCount,b.saleCut,b.tplId,ROUND(b.saleCut*c.miAward,2) AS miAward,d.id as sId,com.deleted as comment")
            ->where($where)
            ->order($order)
            ->limit($pageStart, $limit)
            ->select();
        $count = $miYouQuanModel->alias("a")
            ->join("inner join wx_module_product b on a.vid=b.vId")
//            ->join("INNER JOIN wx_miyouquan c ON c.id=a.quanId")
            ->join("INNER JOIN (SELECT * FROM wx_mishare WHERE module='product') AS d ON d.moduleId=b.id ")
            ->join("LEFT JOIN (SELECT sId as msId,deleted  FROM wx_mirecomment WHERE uId=$uId AND quanId=$qId and deleted=0 ) com ON com.msId=d.id ")
            ->where($where)
            ->order($order)
            ->count();

        $proList = new StdClass();
        $proList->count = $count;
        $proList->pageCount = getPageCount($count, $limit);
        if ($result) {
            $proList->list = $result;
        } else {
            $proList->list = array();
        }
        $proList->type = $type;
        return $proList;
    }

    public function bind()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $IsBind = self::checkBind();
        $location = $IsBind["location"];
        redirect($location);
        return;
    }

    public function checkBind($param = null)
    {
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        $uId = Session::$user['userId'];
        Session::switchCustomer(0);
        $quanUserModel = M("quan_user");
        //根据userName查找对应的微信资料id
        Session::switchCustomer($customerId);
        $weixinUserModel = M("user_weixin_info");
        $weixinUserResult = $weixinUserModel->where("openid='" . $userName . "'")->find();
        if ($weixinUserResult) {
            $quanInfo = $quanUserModel->alias("a")
                ->join("inner join wx_miyouquan b on a.qid =b.id")
                ->field("a.*")
                ->where("a.uid=$uId and a.status=1 and a.deleted =0 and b.cId = $customerId")->find();
            $qId = $quanInfo['qid'];
            if ($param && $param->community) {
                $location = C("SERVER_HOST") . 'call.html?customerId=' . $customerId . '&module=community&method=index&params=%7B"qid"%3A"' . $qId . '"%7D';
            } else {
                $location = C("SERVER_HOST") . 'call.html?customerId=' . $customerId . '&module=quan&method=index&params=%7B"qId"%3A"' . $qId . '"%7D';
            }
            $out["status"] = 0;
            $out["qId"] = $qId;
        } else {
            $qId = $param->qId;
            $fromUId = $param->fromUId;
            $location = C("SERVER_HOST") . "call.html?customerId=$customerId&module=quan&method=mireg&params=%7B%22qId%22%3A%22$qId%22%2C%22fromUId%22%3A%22$fromUId%22%7D";
            $out["status"] = 1;
        }
        $out["location"] = $location;
        return $out;
    }

    /**
     * [sendSmsCode 发送验证码]
     * @param  [type] $mobile [description]
     * @return [type]         [description]
     */
    public function sendSmsCode($mobile, $isCheckExist = true)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $where["phone"] = array('eq', $mobile);
        $result = $userModel->where($where)->find();
        if ($isCheckExist) {
            if (!$result || count($result) < 1) {
                Output::instance()->resultCode(1, '手机用户不存在!');
                return;
            }
        }
        $code = rand(10000, 99999);
        Log::write("注册密友验证码" . $code);
        $msg = "您申请注册密友圈，验证码:" . $code . " (30分钟内有效)。【密友圈】";
        $code = self::getSmsCode($mobile, $msg);
        if ($code) {
            session('smsCode', $code, 60 * 30);
            Output::instance()->resultCode(code_success, $code);
        } else {
            $newResult["code"] = 1;
            $newResult["msg"] = '信息发送失败！';
            Output::instance()->object($newResult);
        }
    }

    //发送短信的接口
    public static function getSmsCode($mobileNum, $msg)
    {
        //此函数功能是群发短信和发单条短信。（传一个手机号就是发单条，多个手机号既是群发）
        //您把序列号和密码还有手机号，填上，直接运行就可以了
        //该方法content接收utf-8编码。如果您的系统是utf-8,则content不用转码直接提交，如果是gb2312编码则要转为utf-8编码再提交
        $flag = 0;
        //要post的数据
        $argv = array(
          'sn'=>'SDK-BBX-010-22218', ////替换成您自己的序列号
		  'pwd'=>strtoupper(md5('SDK-BBX-010-22218'.'6c9-1502')), //此处密码需要加密 加密方式为 md5(sn+password) 32位大写
		  'mobile'=>"$mobileNum",//手机号 多个用英文的逗号隔开 post理论没有长度限制.推荐群发一次小于等于10000个手机号
		  'content'=>iconv( "gb2312", "UTF-8//IGNORE" ,"$msg"),//短信内容
          'content'=>"$msg",//短信内容
		  'ext'=>'1',
		  'stime'=>'',//定时时间 格式为2011-6-29 11:09:21
		  'msgfmt'=>'',
		  'rrid'=>''
		);
 		//构造要post的字符串
        foreach ($argv as $key=>$value) {
          if ($flag!=0) {
            $params .= "&";
            $flag = 1;
          }
          $params.= $key."="; $params.= urlencode($value);
          $flag = 1;
        }
        $length = strlen($params);
        //创建socket连接
        $fp = fsockopen("sdk.entinfo.cn",8061,$errno,$errstr,10) or exit($errstr."--->".$errno);
        //构造post请求的头
        $header = "POST /webservice.asmx/mdsmssend HTTP/1.1\r\n";
        $header .= "Host:sdk.entinfo.cn\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: ".$length."\r\n";
        $header .= "Connection: Close\r\n\r\n";
        //添加post的字符串
        $header .= $params."\r\n";
        //发送post的数据
        fputs($fp,$header);

        $inheader = 1;
        while (!feof($fp)) {
             $line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据
             if ($inheader && ($line == "\n" || $line == "\r\n")) {
                     $inheader = 0;
              }
              if ($inheader == 0) {
                    // echo $line;
              }
        }
		//<string xmlns="http://tempuri.org/">-5</string>
	    $line=str_replace("<string xmlns=\"http://tempuri.org/\">","",$line);
	    $line=str_replace("</string>","",$line);
	    $result=explode("-",$line);
		// echo $line."-------------";
		if(count($result)>1) {
			Log::write('发送失败返回值为:'.$line.'。请查看webservice返回值对照表');
			return "";
		} else {
		  Log::write('发送成功 返回值为:'.$line);
		  return true;
		}
    }
	/**
	 * 获取用户所有的圈
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getQuan($param){
		Output::instance()->module('quan',"quan_list")->object($result);
	}
	public function getQuanList($start,$limit){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		$uId = Session::$user['userId'];
		Session::switchCustomer(0);
		$quanModel=M("quan_user");

		$pageStart=$start*$limit;

		$where["uid"]=array('eq',$uId);
		$where["status"]=array("eq",1);
		$order = 'a.createTime desc';
		$where["deleted"]=array("eq",0);
		$quanList= $quanModel->alias("a")
		->join("inner join wx_miyouquan b on a.qid=b.id")
		->field("b.id,b.name,b.logo,a.activeTime,a.createTime")
		->where($where)
		->order($order)
		->limit($pageStart, $limit)
		->select();

		$count =$quanModel->alias("a")
		->join("inner join wx_miyouquan b on a.qid=b.id")
		->field("b.id,b.name,b.logo")
		->where($where)
		->order($order)
		->count();
		Session::switchCustomer($customerId);
		$quan=new StdClass();
		$quan->count=$count;
		$quan->pageCount=getPageCount($count,$limit);
		$quan->list=$quanList;
		Output::instance()->object($quan);
	}

	//记录用户对商品的巨鹿添加pv统计，uv统计
	public function addViewCount($param){
		$customerId = Session::$user['customerId'];
		$userName=Session::$user['userName'];
		$uid = Session::$user['userId'];
		$sId=$param->sId;
		$miUId=$param->miUId;
		$qId=$param->qId;
		Session::switchCustomer(0);
		$uStaModel=M("mishare_stat");
		$uVisiModel=M("mishare_visit");
		Session::switchCustomer($customerId);
		$result=$uStaModel->where("sId='$sId' and miUid='$miUId'")->find();
		if(!$result) {
			$data=array(
				"sId"=>$sId,
				"miUid"=>$miUId,
				"shareCount"=>0,
				"praiseCount"=>0,
				"quanId"=>$qId,
				"uv"=>0,
				"pv"=>0,
				"createTime"=>date("Y-m-d H:i:s")
			);
			$id=$success=$uStaModel->add($data);
		} else {
			$id=$result["id"];
		}
		$uStaModel->where("id='$id'")->setInc('pv');//pv+1
		//判断是否更新uv
		$visitResult=$uVisiModel->where("uId=$uid and sId=$sId")->find();
		if(!$visitResult && isMicroMessengerUserAgent()) {
			$uStaModel->where("id='$id'")->setInc('uv');//uv+1
			$staResult=$uStaModel->where("id='$id'")->find();
			if($staResult) {
				//触发uv任务
				$p=new StdClass();
				$p->miUId=$param->miUId;
				$p->qId=$qId;
				Log::write("开始调用任务更新");
				Module::callModule("task", Session::$user,"updateTaskStatus", $p);
			}
		}
		return $success;
	}

	/**
	 * 增加访问记录
	 * @param $param
	 * @return mixed
	 */
	public function addVisit($param){
        Session::init();
		$customerId = Session::$user['customerId'];
		$userName=Session::$user['userName'];
		$uid = Session::$user['userId'];
        if(!$customerId){
            Log::write('customerId获取失败');
            $customerId = $_GET['customerId'];
        }
		$sId=$param->sId;
		$miUid = $param->miUId;
		$qId = $param->qId;
		Session::switchCustomer(0);
		$uVisiModel=M("mishare_visit");
		$mimall_user = M("mimall_user");
		$user_statistics = M("user_statistics");
		$moduleInfo = M('mishare')->where(['id' => $sId])->field('module,moduleId')->find();
		if($moduleInfo['module'] == 'product'){
			$title = M('module_product')->where(['id' => $moduleInfo['moduleId']])->getField('name');
		}else if($moduleInfo['module'] == 'micontent'){
			$title = M('micontent')->where(['id' => $moduleInfo['moduleId']])->getField('title');
		}else if($moduleInfo['module'] == 'mall'){
			$title = M('wx_'.$customerId.'_material')->where(['id' => $moduleInfo['moduleId']])->getField('name');
		}else{
            $title = $param->title;
		}
//		/** 获取销售源id*/
//		$saleSourceUid = $mimall_user->where("uId=$uid and cId=$customerId")->getField("saleSource");

		$ipInfo = self::getIp_agent();
		$data=array(
//			"fromGuid"=>$param->fromGuid,
//			"guid"=>$param->guid,
            "sId" => $param->sId,
            "cid" => $customerId,
            "module" => $moduleInfo['module'],
            "moduleId" => $moduleInfo['moduleId'],
            "title" => $title,
            "uId" => $uid,
            "miUid" => $param->miUId,
            "saleSourceUid" => $param->saleSourceUid,
            "visitId" => $param->visitId,
            "fromPage" => $param->fromPage,
            "createTime" => date("Y-m-d H:i:s"),
            "ip" => $ipInfo['ip_address'],
            "address" => $ipInfo['province'] . '-' . $ipInfo['city'],
            "leaveTime" => date("Y-m-d H:i:s")
        );
        Session::switchCustomer($customerId);
        $success = $uVisiModel->add($data);
        if ($success) {
            $param->cid = $customerId;
            $param->uid = $uid;
            $param = json_encode($param);
            $redis = new RedisAPI();
            $redis->rPush('shareStatis', $param);
            //更新浏览数  LP改为redis异步更新浏览数
//            self::addViewCount($param);
//            self::updateViewCount($param);
        }
        Session::switchCustomer($customerId);
        return $success;
    }

    /**
     * 获取用户的ip以及user_agent信息
     * @return array
     */
    protected static function getIp_agent()
    {
        $ipInfo = array();
        if ($_SERVER['HTTP_HTTP_X_REAL_IP']) {
            //nginx 代理模式下，获取客户端真实IP
            $realIp = $_SERVER['HTTP_HTTP_X_REAL_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            //客户端的ip
            $realIp = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_HTTP_X_FORWARDED_FOR'])) {
            //浏览当前页面的用户计算机的网关
            $arr = explode(',', $_SERVER['HTTP_HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $realIp = trim($arr[0]);
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            //浏览当前页面的用户计算机的ip地址
            $realIp = $_SERVER['REMOTE_ADDR'];
        } else {
            $realIp = $_SERVER['REMOTE_ADDR'];
        }
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $realIpInt = bindec(decbin(ip2long($realIp)));

        //查询ip对应的地址信息
        if ($realIp) {
            $cid = Session::$user['customerId'];
            Session::switchCustomer(0);
            $ipInfo_table = M('ip_info');

            $map = array();
            $map['start_ip_int'] = array('elt', $realIpInt);
            $map['end_ip_int'] = array('egt', $realIpInt);
            $result = $ipInfo_table->where($map)->find();
            if ($result) {
                $ipInfo['province'] = $result['province'];
                $ipInfo['city'] = $result['city'];
            } else {
                Log::write('客户端ip信息----:' . serialize($_SERVER));
                Log::write('查询ip信息-----' . $ipInfo_table->getLastSql());
            }
            Session::switchCustomer($cid);
        }

        $ipInfo['ip_address'] = $realIp;
        $ipInfo['userAgent'] = $userAgent;
        return $ipInfo;
    }

    public function visitLeaveTime($id, $leaveTime)
    {
        Session::switchCustomer(0);
        $uVisiModel = M("mishare_visit");
        $lastLeaveTime = $uVisiModel->where(['id' => $id])->getField('leaveTime');
        $visitTime = strtotime($leaveTime) - strtotime($lastLeaveTime);
        $date['visitTime'] = $visitTime;
        $date['leaveTime'] = $leaveTime;
        $uVisiModel->where(['id' => $id])->save($date);

    }

//	public function lev

	/**
	 * [updateViewCount 更新浏览数]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function updateViewCount($param){
		$sId=$param->sId;
		$uid = Session::$user['userId'];
		$miUId=$param->miUId;
		$lastShareUid=$param->lastShareUId;
		$visitId=$param->visitId;

		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$sModel=M("mishare");
		$sFromModel=M("mishare_from");
		$uVisiModel=M("mishare_visit");

		Session::switchCustomer($customerId);
		$sModel->where('id=' .$sId)->setInc('viewCount');
		if($uid==$lastShareUid){
			return;
		}

		$visitResult=$uVisiModel->where("uId=$uid and sId=$sId and cid=$customerId")->count();
//		if(!$visitResult && isMicroMessengerUserAgent()) {
		if($visitResult==1) {
			$sModel->where('id=' .$sId)->setInc('viewUv');//mishare总表 uv+1
//			$staResult=$uStaModel->where("id='$id'")->find();
//			if($staResult) {
//				//触发uv任务
//				$p=new StdClass();
//				$p->miUId=$param->miUId;
//				$p->qId=$qId;
//				Log::write("开始调用任务更新");
//				Module::callModule("task", Session::$user,"updateTaskStatus", $p);
//			}
		}


        if(!empty($visitId)){
            $id = $sFromModel->where(['visitId' => $visitId, 'uid' => $lastShareUid])->getField('id');
            $sFromModel->where(['visitId' => $visitId, 'id' => $id])->setInc('viewCount');	//针对与分享记录浏览次数 +1
			$count = $uVisiModel->where(['visitId' => $visitId, 'uId' => $uid])->count(); //查看
			if($count == 1){
				$sFromModel->where(['visitId' => $visitId, 'id' => $id])->setInc('viewUv');
			}
		}
	}

	/**
	 * [getProView 引导页面]
	 * @param  [type] $sId [description]
	 * @return [type]      [description]
	 */
	public function getGuideView($param,$fromPage="guide"){
		$customerId = Session::$user['customerId'];
		$userName=Session::$user['userName'];
		$sId=$param->id;
		Session::switchCustomer(0);
		$shareModel=M("mishare");
		$productModel=M("module_product");
		$where["a.id"]=array('eq',$sId);

		$result=$shareModel->alias("a")
		->join("inner join wx_pb_template c on c.id=a.tplId")
		->join("left join wx_mishare_material b on b.sId=a.id")
		->field("a.*,b.shareImg,b.shareImg1,c.htmlname")
		->where($where)->find();
		if (!$result) {
			Output::instance()->resultCode(1,'分享不存在');
			return;
		}
		if(!$result["shareImg"] && $result["module"]=="product") { //如果没有引导页面,跳转商品详情页面
			$pid=$result["moduleId"];
			$product=$productModel->where("id=$pid")->find();
			$fromCustomerId=$product["fromCustomerId"];
			$p=new StdClass();
			$p->id=$pid;
			$p->qId=$param->qId;
			$p->miUId=$param->miUId;
			$p->sId=$sId;
			$p=urlencode(json_encode($p));
			$location=C("SERVER_HOST") . 'call.html?customerId='.$fromCustomerId.'&module=product&method=getProduct&params='.$p;
			redirect($location);
		}
		Session::switchCustomer($customerId);
		$tplName="quan_guideView";
		$Guid = new Guid();
		$result["guid"] = $Guid->toString();//分享用的id
		$module=$result["module"];
		if($result) {
			//获取分享具体内容
			$param->id=$result["moduleId"];
			$param->sId=$sId;
			$detail = Module::callModule($module, Session::$user,"getObjectDetail", $param);
			//添加一次浏览记录
			$result["sId"]=$sId;
			$visitParam=new StdClass();
			$visitParam->guid=$result["guid"];
			$visitParam->sId=$sId;
			$visitParam->fromPage="guide";
			$visitParam->miUId=$param->miUId;
			$visitParam->qId=$param->qId;
			$visitParam->fromGuid=$param->fromGuid;

			$visitid=self::addVisit($visitParam);

			$result=array_merge($result,$detail);
			$tplName=$result["htmlname"];

			Output::instance()->module('quan',$tplName)->object($result);
		}
	}
	public function getGuideViewImgs($param){
		$customerId = Session::$user['customerId'];
		$userName=Session::$user['userName'];
		$sId=$param->sId;
		Session::switchCustomer(0);
		$shareModel=M("mishare_material");
		$where["a.sId"]=array('eq',$sId);

		$result=$shareModel->alias("a")
		->where($where)->find();
		if (!$result) {
			Output::instance()->resultCode(1,'分享不存在');
			return;
		}
		Session::switchCustomer($customerId);
		Output::instance()->object($result);
	}
	/**
	 * [saveShare 保存一次分享]
	 * @param  [type] $sId  [description]
	 * @param  [type] $qId  [description]
	 * @param  [type] $guid [description]
	 * @return [type]       [description]
	 */
	public function saveShare($param){
        Log::write('saveShare-----:'.print_r($param, true));
		$customerId = Session::$user['customerId'];
		$userName=Session::$user['userName'];
		$uid = Session::$user['userId'];
		$sId=$param->sId;
		$qId=$param->qId;
		Session::switchCustomer(0);
		$uShareModel=M("mishare_from");
		$uStaModel=M("mishare_stat");
		$visitModel=M("mishare_visit");
		$sModel=M("mishare");
		$recommentModel=M("mirecomment");
		$mimall_user=M("mimall_user");

//		$guid=$param->guid;
        $miUId = $param->miUId;
        $lastShareUId = $param->lastShareUId;
        $saleSourceUid=$param->saleSourceUid;
        $visitId = $param->visitId;
        $vId = $visitModel->where(['id' => $visitId])->getField('visitId');
        $lastShare = $uShareModel->where(['visitId' => $vId])->find();
        if ($lastShare["path"]) {
            $path = $lastShare["path"] . "-" . $uid;
        } else {
            $path = $uid;
        }
        $moduleInfo = M('mishare')->where(['id' => $sId])->field('module,moduleId')->find();
        if ($moduleInfo['module'] == 'product') {
            $title = M('module_product')->where(['id' => $moduleInfo['moduleId']])->getField('name');
        } else if ($moduleInfo['module'] == 'micontent') {
            $title = M('micontent')->where(['id' => $moduleInfo['moduleId']])->getField('title');
        } else if ($moduleInfo['module'] == 'mall') {
            $title = M('wx_' . $customerId . '_material')->where(['id' => $moduleInfo['moduleId']])->getField('name');
        }else if($moduleInfo['module'] == 'miContentShow'){
            $title = M('wx_micontent_show')->where(['id' => $moduleInfo['moduleId']])->getField('name');
        }
        /** 获取销售源id*/
//        $saleSourceUid = $mimall_user->where("uId=$uid and cId=$customerId")->getField("saleSource");

//		$lastShareUId = $visitModel->where(['id' =>$visitId])->getField('uid');
        $data = array(
//			'guid' =>$guid,
            'sId' => $sId,
            'cid' => $customerId,
            'viewCount' => 0,
            'praiseCount' => 0,
            'commentCount' => 0,
            'uId' => $uid,
            'miUid' => $param->miUId,
            'createTime' => date("Y-m-d H:i:s"),
            'saleSourceUid' => $saleSourceUid,
            'lastShareUid' => $lastShare['uId'],
            'visitId' => $visitId,
            'path' => $path,
            'fromPage' => $param->fromPage,
            'quanId' => $param->qId,
            'shareType' => $param->shareType,
            'module' => $moduleInfo['module'],
            'moduleId' => $moduleInfo['moduleId'],
            'title' => $title
        );
        $success = $uShareModel->add($data);
        Session::switchCustomer($customerId);
        if ($success) {
            self::shareCount($success);
            $sModel->where('id=' . $sId)->setInc('shareCount');
            $fromResult=$uShareModel->where("uId=$uid and sId=$sId and cid=$customerId")->count();
            if($fromResult==1) {
                $sModel->where('id=' . $sId)->setInc('shareUv');//mishare总表 uv+1
            }
            $uStaModel->where("sId=$sId and miUid=$miUId")->setInc('shareCount');
            $Guid = new Guid();
            $guid = $Guid->toString();
            $out = new StdClass();
            $out->guid = $guid;
            $out->code = 0;
            Output::instance()->object($out);
        }else{
            Log::write('saveShare保存分享数据失败:'.$uShareModel->getDbError());
        }//分享保存到个人推荐中
        $addData = array(
            "uId" => $uid,
            "quanId" => $qId,
            "sId" => $sId,
            "createTime" => date("Y-m-d H:i:s"),
            "deleted" => 0
        );
        $rs = $recommentModel->where("uId='$uid' and quanId='$qId' and sId='$sId'")->find();
        if (!$rs || count($rs) < 1) { //防止重复插入
            $recommentModel->add($addData);
        }
    }
    public function shareCount($shareId)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uShareModel = M("mishare_from");
        $user_statistics = M("user_statistics");
        $miu_statistics = M("miu_statistics");
        $salesource_statistics = M("salesource_statistics");
        $quan_user = M("quan_user");
        Session::switchCustomer($customerId);
        $shareInfo = $uShareModel->where(['id' => $shareId])->find();
        $uid = $shareInfo['uId'];
        $cid = $shareInfo['cid'];
        $saleSourceUid = $shareInfo['saleSourceUid'];
        if ($uid) {
            //分享人分享数量+1
            $result = R("StatisTics/checkUser", array($uid, $cid));
            if ($result) {
                $statiInfo['uid'] = $uid;
                $statiInfo['cid'] = $cid;
                $user_statistics->add($statiInfo);
            }
            $user_statistics->where(['cid' => $cid, 'uid' => $uid])->setInc('shareCount');
        }

        //查询是否为注册好友,如果为注册好友 则给分享人注册好友身份分享数量+1
        $where['b.cId'] = array('eq', $cid);
        $where['a.uId'] = array('eq', $uid);
        $where['a.deleted'] = array('eq', 0);
        $userInfo = $quan_user->alias('a')->where($where)->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
        if (!empty($userInfo['qid']) && $uid) {
            $result = R("StatisTics/checkMiU", array($uid, $cid));
            if ($result) {
                $data['uid'] = $uid;
                $data['cid'] = $cid;
                $miu_statistics->add($data);
            }
            /** 5.添加密友分享总次数*/
            $miu_statistics->where(['uid' => $uid, 'cid' => $cid])->setInc('shareCount');
        }
        if($saleSourceUid){
            //销售员分享数量+1
            $result = R("StatisTics/checkSaleSource", array($saleSourceUid, $cid));
            if ($result) {
                $statiInfo['uid'] = $saleSourceUid;
                $statiInfo['cid'] = $cid;
                $salesource_statistics->add($statiInfo);
            }
            $salesource_statistics->where(['cid' => $cid, 'uid' => $saleSourceUid])->setInc('shareCount');
        }

    }

    /**
     * [getOrderList 获取密友订单页面]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function orderPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//		self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        Session::switchCustomer(0);
        $quanUser = M("quanUser");
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $result["qId"] = $qId;
        $result["fromUId"] = $uid;
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "quanOrder")->object($result);
    }

    /**
     * [getOrderList 获取主公订单页面]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function orderPageAward($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        Session::switchCustomer(0);
        $result["qId"] = $qId;
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "quanOrderAward")->object($result);
    }

    /**
     * [getOrderList 获取主公或者密友订单列表]
     * @param  [type] $param [description]
     * @param  int $type 1.密友的普通订单/主公订单
     * @param  int $orderType 0普通订单/1.营销订单
     * @return [type]        [description]
     */
    public function getOrderList($qId, $type, $start, $limit, $status = 0, $search = null, $saleSource = 0, $orderType=0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $order = "a.createTime desc";
        $pageStart = $start * $limit;
        $where["a.qId"] = array('eq', $qId);
        $where["a.deleted"] = array('eq', 0);
        $search ? $where["b.name"] = array("like", "%" . $search . "%") : "";
        if($orderType == 1){
            unset($where['b.name']);
            $search ? $where["a.serialNumber"] = array("like", "%" . $search . "%") : "";
        }
//		if($search){
//			$condition['_logic'] = 'OR';
//			$condition["a.phone"]=array("eq",$search);
//			$condition["a.fullName"]=array("like",'%'.$search.'%');
//			$condition["c.name"]=array("like","%".$search."%");
//			$where["_complex"]=$condition;
//		}
        switch ($status) {
            case 0:
                $where["a.status"] = array("eq", 'teaming');
                break;
            case 1:
                if($orderType == 1){
                    $where["a.status"] = array(array("eq", order_status_delivering), array("eq", order_status_submission), "or");
                }else{
                    $where["a.status"] = array(array("eq", order_status_delivering), array("eq", order_status_deliveringtostore), array("eq", order_status_ordersign), array("eq", "supported"), "or");
                };
                break;
            case 2:
                $where["a.status"] = array(array("eq", order_status_delivered), array("eq", order_status_deliveredtostore), "or");
                break;
            case 3:
                $where["a.status"] = array(array("eq", order_status_ok), array("eq", order_status_confirmsign), 'or');
                break;
            case 4:
                $where["_string"] = "a.status='" . order_status_refund . "' or a.status='" . ORDER_STATUS_REFUNDEDPART . "' or a.status='" . ORDER_STATUS_REFUNDING . "'";
                break;
            case 5: //已取消
                $where["a.status"] = order_status_cancel;
                break;
        }
        if($orderType == 1){
            $where['a.type'] = ORDER_TYPE_FORM;  //营销订单
        }else{
            $where['a.type'] = ['neq', ORDER_TYPE_FORM];
        }
        if ($type == 1) { //密友订单列表
            $condition['_logic'] = 'OR';
            if ($saleSource) {
                $condition["a.saleSource"] = array("eq", $uId);
            } else {
                /*if($orderType == 1){
                    $condition["a.uId"] = array("eq", $uId);        //营销订单中密友订单包含自己的订单
                }*/
                $condition["a.miUid"] = array("eq", $uId);
                $condition["a.refereeUid"] = array("eq", $uId);
                $condition["a.parentRefereeUid"] = array("eq", $uId);
            }
            $where["_complex"] = $condition;
            $orderList = $orderModel->alias("a")
                ->join("inner join wx_module_product_order_detail b on a.id =b.oid")
                ->where($where)
                ->field("a.*")
                ->order($order)
                ->group("a.id")
                ->limit($pageStart, $limit)
                ->select();
            Log::write('jie--order'.$orderModel->getLastSql());
            $count = $orderModel->alias("a")
                ->join("inner join wx_module_product_order_detail b on a.id =b.oid")
                ->where($where)
                ->order($order)
                ->count("a.id");
            Log::write('jie--order'.$orderModel->getLastSql());
        } else {
            $orderList = $orderModel->alias("a")
                ->join('inner join wx_quan_user b on a.miUid=b.uid and a.qId=b.qid')
                ->join("inner join wx_module_product_order_detail d on a.id =d.oid")
                ->field("a.*,b.nickName,b.headImgUrl")
                ->where($where)
                ->order($order)
                ->limit($pageStart, $limit)
                ->select();
            $count = $orderModel->alias("a")
                ->join('inner join wx_quan_user b on a.miUid=b.id')
                ->join("inner join wx_module_product_order_detail b on a.id =b.oid")
                ->where($where)
                ->order($order)
                ->count("a.id");
        }
        foreach ($orderList as $key => $val) {
            $proList = self::getProductByOrderId($val["id"]);
            $orderList[$key]["productList"] = $proList;
        }

        Session::switchCustomer($customerId);
        $order = new StdClass();
        $order->count = $count;
        $order->pageCount = getPageCount($count, $limit);
        Log::write('jie--order-3'.print_r($order, true));
        $order->orderList = $orderList;
        $order->uType = $type;
        $order->uId = $uId;
        Output::instance()->object($order);
    }

    public function getProductByOrderId($orderId, $isGetPath = 0)
    {
        $orderModel = M("module_product_order");
        $proList = $orderModel->alias("a")
            ->join('inner join wx_module_product_order_detail b on a.id=b.oid')
            ->join('left join wx_module_product_order_detail_specification as sp on sp.did=b.id')
            ->join('wx_miyouquan q on q.id=a.qId')
            ->field("a.fromUserName,b.pid,b.name,ROUND((b.price*b.count), 2) as price,b.picUrl1,ROUND((b.isRefereeCut),2) as refereeAward,ROUND((b.isParentRefereeCut),2) as parentRefereeAward,
			b.picUrl,ROUND((b.saleCut),2) as saleCut,ROUND((b.platCut),2) as platCut,ROUND((b.isMiUserCut),2) as miAward,ROUND((b.isLordCut),2) as lordAward,b.sId,a.fromCustomerId,b.count,sp.firstSpecificName,
			b.shareFromGuid,ROUND((b.discountedPrice*b.count),2) as disTotal,ROUND((b.fixedPrice*b.count),2) as fixedTotal,
			sp.secSpecificName,b.id as did, b.customizedInfo")
            ->where('oid=' . $orderId)
            ->order($order)
            ->select();
        foreach ($proList as $key => $pro) {
            $proList[$key]['isComment'] = self::getUserComment($orderId, $pro['pid'], $pro['fromUserName'], $pro['did']);
            if($pro['customizedInfo']){
                $proList[$key]['customizedInfo'] = json_decode($pro['customizedInfo'], true);
            }
        }
//		if($isGetPath) {
//			foreach ($proList as $key=>$pro) {
//				$paths=self::getProductProcess($pro["shareFromGuid"],$orderId);
//				$proList[$key]["paths"]=$paths;
//			}
//		}
        if ($proList) {
            return $proList;
        }
    }

    /**
     * 获取用户留言
     * @param $oid
     * @param $pid
     * @param $fromUserName
     * @param $did
     * @return int
     */
    public function getUserComment($oid, $pid, $fromUserName, $did)
    {
        $ProductCommentModel = M("module_product_comment");
        $orderModel = M("module_product_order");
        $orderDetailModel = M("module_product_order_detail");
        $commentConfig = M("module_comment_config");
        $uid = Session::$user['userId'];
        $condition["oid"] = array('eq', $oid);
        $condition["pid"] = array('eq', $pid);
        $condition["type"] = array('eq', 1);
        $condition["fromUserName"] = array('eq', $fromUserName);
        $orderInfo = $orderModel->where("id=$oid")->field("status,completionTime,fromCustomerId,miUid,completionTime")->find();
        $configInfo = $commentConfig->where("customerId=" . $orderInfo['fromCustomerId'])->find();
        $completionTime = strtotime($orderInfo['completionTime']);
        $day = $configInfo['validityDays'];
        $now = date("Y-m-d H:i:s");
        $now = strtotime("$now -$day day");
        if ($orderInfo['status'] != order_status_ok || $now > $completionTime || $orderInfo['miUid'] != $uid || strtotime($orderInfo['completionTime']) < strtotime("2017-02-15 00:00:00")) {
            return 2;
        }
        $productInfo = $orderDetailModel
            ->where("id=$did")
            ->field("price,count")
            ->find();
        if ($productInfo['price'] * $productInfo['count'] <= $configInfo['singleProductAmount']) {
            return 2;
        }
        $result = $ProductCommentModel->where($condition)->find();
        if ($result && count($result) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    public function getProductProcess($formGuid, $orderId)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $miShareFrom = M("mishare_from");
        $orderModel = M("module_product_order");

        Session::switchCustomer($cid);
        $userModel = M("user");
        if ($formGuid) {
            $where["guid"] = $formGuid;
            $arr = $miShareFrom->where($where)->find();
            $path = $arr["path"];
            $path = $path . '-' . $arr["id"];
            $path = str_replace("-", ",", $path);
            $whereres["mf.id"] = array('in', $path);

            Log::write($miShareFrom->getlastsql());

            $res = $miShareFrom->alias("mf")->field("wx.nickname,wx.headimgurl,mf.createTime")
                ->join("wx_" . $cid . "_user as au  on au.id=mf.uid")
                ->join("wx_" . $cid . "_user_weixin_info as wx  on wx.userId=au.id")
                ->where($whereres)
                ->order("instr('" . $path . "',mf.id)")->select();
            $out["shareList"] = $res;
        }

        Log::write($miShareFrom->getlastsql());
        //获取购买者
        $orderList = $orderModel->where("id=$orderId")->find();
        if ($orderList) {
            $orderWhere['openid'] = array("eq", $orderList['fromUserName']);
            $userBuy = M('')->table("wx_" . $orderList['fromCustomerId'] . "_user_weixin_info")->where($orderWhere)->field("nickname,headimgurl")->find();
            if (!$userBuy && $orderList["uId"]) {
                $buyUserId = $orderList["uId"];
                $userBuy = $userModel->alias("a")
                    ->join("wx_" . $cid . "_user_weixin_info as b  on b.userId=a.id")
                    ->field("b.nickname,b.headimgurl")
                    ->where("a.id=$buyUserId")
                    ->find();
            }
            if ($userBuy) {
                $out["buyInfo"] = $userBuy;
            }
        }
        return $out;
    }

    /**
     * 密友圈获取订单详情
     * @param $oid  /订单id
     * @param $uType    /密友类型
     * @param null $fromUId
     */
    public function getOrderDetail($oid, $uType, $fromUId = null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        Session::switchCustomer(0);
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        $OrderModel = M("module_product_order");
        $quanUser = M("quan_user");
        $whereOrder["id"] = array('eq', $oid);
        $order = $OrderModel
            ->where($whereOrder)
            ->find();
        $orderCid = $order['fromCustomerId'];
        $buyUser = $quanUser->table("wx_" . $orderCid . "_user_weixin_info")->where("openid = '" . $order['fromUserName'] . "'")->find();
        $miUser = $quanUser->where("qid = " . $order['qId'] . " and uid = " . $order['miUid'])->find();
        if (!$order) {
            Output::instance()->resultCode(code_product_order_not_exist);
            return;
        }
        $productList = self::getProductByOrderId($oid, 1);
        $order["productList"] = $productList;
        $order["uType"] = $uType;
        //$fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $qId = $order["qId"];
        $param->qId = $qId;
        $result = self::getUserInfo($param);
        $order["fromUId"] = $uid;
        $order["headImgUrl"] = $result["headImgUrl"];
        $order["qId"] = $qId;
        $order["uid"] = $uId;
        $order['buyUser'] = $buyUser;
        $order['miUser'] = $miUser;
        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "quan_OrderDetail")->object($order);
    }

    /**
     * [quanAwardIndex 主公页面]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function quanAwardIndex($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userInfo = self::getUserInfo($param);
        if ($userInfo["identity"] != 0) {
            Output::instance()->resultCode(1, "无权限！");
            return;
        }
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        $userName = Session::$user['userName'];
        $weixinUserModel = M("user_weixin_info");
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $where["identity"] = array('eq', 0);
        $where["status"] = array('eq', 1);
        $where["deleted"] = array('eq', 0);
        $result = $quanModel->alias("a")
            ->join("inner join wx_miyouquan b on b.id=a.qid")
            ->field("b.logo,b.coins,b.name,a.*")
            ->where($where)->find();

        $where1["qid"] = array('eq', $qId);
        $where1["identity"] = array('eq', 1);
        $where1["deleted"] = array('eq', 0);
        $where1["status"] = array('eq', 1);

        $count = $quanModel->alias("a")
            ->join("inner join wx_" . $customerId . "_user b on a.uid=b.id")
            ->where($where1)
            ->count();

        Session::switchCustomer($customerId);
        $result["qId"] = $qId;
        $result["count"] = $count;
        Output::instance()->module('quan', "quanAwardIndex")->object($result);
    }

    /**收支主页*/
    public function balanceIndex($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//		self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        $result["qId"] = $qId;
        $result["uType"] = $param->uType;
        Output::instance()->module('quan', "balance")->object($result);
    }

    public function getBalanceSum($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        $uType = $param->uType;
        Session::switchCustomer(0);
        $quanuser = M("quan_user");
		$customer_setting = M("customer_setting");
        $miyouquan = M("miyouquan");
        if ($uType == 1) {
            $result = $quanuser->where("qid = $qId and uid = $uid and deleted = 0")->field("ROUND(totalTixian,2) as outT,ROUND(totalRevenue,2) as inM,ROUND(miCoins,2) as miCoins")->find();
			$withdrawConfig = $customer_setting->where("cid=$customerId")->getField('withdrawConfig');
			$withdrawConfig = json_decode($withdrawConfig,true);
			$result['withdrawType'] = $withdrawConfig['withdrawType'];
		} else {
            $result = $miyouquan->where("id=$qId")->field("ROUND(totalTixian,2) as outT,ROUND(totalRevenue,2) as inM,ROUND(coins,2) as miCoins")->find();
        }
//		$ROUND='ROUND(SUM(money),2)';
//		$rs=$uModel->query("SELECT $ROUND AS m FROM $tableName a WHERE `type`=0 AND quanId=".$qId.$uidstr. " AND createTime BETWEEN DATE_ADD(CURDATE(), INTERVAL - DAY(CURDATE()) + 1 DAY) AND LAST_DAY(CURDATE())"); //本月
//		if($rs && count($rs) > 0 && $rs[0]["m"]){
//			$result["inMM"]=$rs[0]["m"];
//		} else{
//			$result["inMM"]=0;
//		}
//		$rs=$uModel->query("SELECT $ROUND AS m FROM $tableName a WHERE `type`=1 AND quanId=".$qId.$uidstr); //累计
//		if($rs && count($rs) > 0 && $rs[0]["m"]){
//			$result["outM"]=abs($rs[0]["m"]);
//		}else {
//			$result["outM"]=0;
//		}
//		$rs=$uModel->query("SELECT $ROUND AS m FROM $tableName a WHERE `type`=1 AND quanId=".$qId.$uidstr. " AND createTime BETWEEN DATE_ADD(CURDATE(), INTERVAL - DAY(CURDATE()) + 1 DAY) AND LAST_DAY(CURDATE())"); //本月
//		if($rs && count($rs) > 0 && $rs[0]["m"]){
//			$result["outMM"]=abs($rs[0]["m"]);
//		} else {
//			$result["outMM"]=0;
//		}
//		$uidstr=" AND a.uId=".$uid;
//		if($uType==1){ //密友提现
//			$rs=$uModel->query("SELECT ROUND(SUM(cash),2) AS m FROM wx_miconis_tixian a inner join wx_quan_user b on a.uid=b.uid and a.quanId=b.qId WHERE quanId=".$qId.$uidstr . " and b.identity=1 AND a.createTime BETWEEN DATE_ADD(CURDATE(), INTERVAL - DAY(CURDATE()) + 1 DAY) AND LAST_DAY(CURDATE())"); //本月
//			if($rs && count($rs) > 0 && $rs[0]["m"]){
//				$result["outMT"]=$rs[0]["m"];
//			} else {
//				$result["outMT"]=0;
//			}
//		} else {
//			$rs=$uModel->query("SELECT ROUND(SUM(cash),2) AS m FROM wx_miconis_tixian  a inner join wx_quan_user b on a.uid=b.uid and a.quanId=b.qId  WHERE quanId=".$qId.$uidstr." and b.identity=0 AND a.createTime BETWEEN DATE_ADD(CURDATE(), INTERVAL - DAY(CURDATE()) + 1 DAY) AND LAST_DAY(CURDATE())"); //本月
//			if($rs && count($rs) > 0 && $rs[0]["m"]){
//				$result["outMT"]=$rs[0]["m"];
//			} else {
//				$result["outMT"]=0;
//			}
//		}
        Session::switchCustomer($customerId);
        Output::instance()->object($result);
    }

    public function getBalanceList($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//		self::checkMUserAuth($param);
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        $qId = $param->qId;
        $uType = $param->uType;
        $tType = $param->tType;
        $start = $param->start;
        $limit = $param->limit;
        $result["qId"] = $qId;
        Session::switchCustomer(0);
        $uModel = M("miaccount_friend");
        $tableName = "wx_miaccount_friend";
        $uidstr = " AND uId=" . $uid;
        $ROUND = 'ROUND(SUM(money),2)';
        if ($uType == 2) {
            $uModel = M("miaccount_lord");
            $tableName = "wx_miaccount_lord";
            $uidstr = "";
        }
        if ($uType == 1) {
            $where["uId"] = array('eq', $uid);
        }
        $where["quanId"] = array('eq', $qId);
        if ($tType == 1) {
            $type= '0,1';
            $where["type"] = array('in', $type);
            $typestr = "type in (0,1)";
        }
//        if ($tType == 2) {
//            $where["type"] = array('eq', 1);
//            $typestr = "type=1";
//        }
        if ($tType == 3) { //主公和密友体现记录，走体现表

            $uidstr = " AND uId=" . $uid;
            $where["uId"] = array('eq', $uid);
            $uModel = M("miconis_tixian");
            $result = $uModel->where($where)
                ->field("*,ROUND(cash,2) as money")
                ->order("createTime desc,id desc")
                ->limit($start, $limit)
                ->select();
            $count = $uModel->where($where)
                ->count();
            if ($result && count($result) > 0) {
                //累计提现
                $rs = $uModel->query("SELECT ROUND(SUM(cash),2) AS m FROM wx_miconis_tixian WHERE  quanId=" . $qId . $uidstr); //累计
                if ($rs && count($rs) > 0 && $rs[0]["m"]) {
                    $out["outT"] = $rs[0]["m"];
                } else {
                    $out["outT"] = 0;
                }
            }
        } else {
            $result = $uModel->where($where)
                ->field("*,ROUND(money,2) as money")
                ->order("createTime desc,id desc")
                ->limit($start, $limit)
                ->select();
            $count = $uModel->where($where)
                ->count();
            if ($result && count($result) > 0) {
                //累计收入支出
                $rs = $uModel->query("SELECT ROUND(SUM(money),2) AS m FROM $tableName WHERE $typestr and quanId=" . $qId . $uidstr); //累计
                if ($rs && count($rs) > 0 && $rs[0]["m"]) {
                    $out["outT"] = $rs[0]["m"];
                } else {
                    $out["outT"] = 0;
                }
            }
        }
        Session::switchCustomer($customerId);
        $out["rs"] = $result;
        $out["tType"] = $tType;
        $out["uType"] = $uType;
        $out["total"] = $count;
        Output::instance()->module('quan', "balanceList")->object($out);
    }

    public function miPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $qId = $param->qId;
        $userInfo = self::getUserInfo($param);

        $where1["qid"] = array('eq', $qId);
        $where1["identity"] = array('eq', 1);
        $where1["deleted"] = array('eq', 0);
        $where1["status"] = array('eq', 1);

        $where2["qid"] = array('eq', $qId);
        $where2["identity"] = array('eq', 1);
        $where2["status"] = array('eq', 1);
        $where2["deleted"] = array('eq', 1);

        $where2["qid"] = array('eq', $qId);

        $where3["qid"] = array('eq', $qId);
        $where3["identity"] = array('eq', 1);
        $where3["status"] = array('eq', 0);
        $where3["deleted"] = array('eq', 0);

        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $uModel = M("quan_user");
        Session::switchCustomer($customerId);

        $count1 = $result = $uModel->alias("a")
            ->join("inner join wx_" . $customerId . "_user b on a.uid=b.id")
            ->where($where1)
            ->count();

        $count2 = $result = $uModel->alias("a")
            ->join("inner join wx_" . $customerId . "_user b on a.uid=b.id")
            ->where($where2)
            ->count();

        $count3 = $result = $uModel->alias("a")
            ->join("inner join wx_" . $customerId . "_user b on a.uid=b.id")
            ->where($where3)
            ->count();

        $out["qId"] = $qId;
        $out["count1"] = $count1;
        $out["count2"] = $count2;
        $out["count3"] = $count3;
        if ($userInfo["identity"] != 0) {
            Output::instance()->resultCode(1, "无权限！");
        } else {
            Output::instance()->module('quan', "mifriendList")->object($out);
        }
    }

    /**
     * [getMiFList 获取密友成员列表]
     * @param  [type]  $qId       [description]
     * @param  integer $orderType [description]
     * @param  string $orderBy [description]
     * @param  integer $start [description]
     * @param  integer $limit [description]
     * @return [type]             [description]
     */
    public function getMiFList($qId, $status = 0, $start = 0, $limit = 10, $search = '')
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        if(!empty($search)){
            $map['b.fullName'] = array("like", "%" . $search . "%");
            $map['b.phone'] = array("like", "%" . $search . "%");
            $map['a.nickName'] = array("like", "%" . $search . "%");
            $map['_logic'] = "OR";
            $where["_complex"] = $map;
        }
        $where["a.qid"] = array('eq', $qId);
        $where["a.identity"] = array('eq', 1);
        if ($status == 0) {
            $where["a.deleted"] = array('eq', 0);
            $where["a.status"] = array('eq', 1);
        } else if ($status == 1) {
            $where["a.status"] = array('eq', 1);
            $where["a.deleted"] = array('eq', 1);
        } else if ($status == 20) {
            $where["a.deleted"] = array('eq', 0);
        } else {
            $where["a.status"] = array('eq', 0);
            $where["a.deleted"] = array('eq', 0);
        }
        $uId = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $friendsAliasModel = M('friends_alias');
        $uModel = M("quan_user");
        Session::switchCustomer($customerId);

        $pageStart = $start * $limit;
        $result = $uModel->alias("a")
            ->join("inner join wx_" . $customerId . "_user b on a.uid=b.id")
            ->where($where)
            ->field("b.fullName,b.phone,a.*,ROUND(a.miCoins,2) as miCoins")
            ->order("createTime desc")
            ->limit($pageStart, $limit)
            ->select();

        if ($result) {
            foreach ($result as $key => $value) {
                $aliasName = $friendsAliasModel->where(['cid' => $customerId, 'userId' => $uId, 'friendId' => $value['uid']])->getField('alias');
                $result[$key]['aliasName'] = $aliasName;
            }
        }

        $count = $uModel->alias("a")
            ->join("inner join wx_" . $customerId . "_user b on a.uid=b.id")
            ->where($where)
            ->count();
        if ($result) {
            $out["list"] = $result;
            $out["qId"] = $qId;
            $out["count"] = $count;
            $out["pageCount"] = getPageCount($count, $limit);
        } else {
            $out["list"] = array();
            $out["qId"] = $qId;
            $out["count"] = 0;
            $out["pageCount"] = 0;
        }
        Output::instance()->object($out);
    }

    public function cashPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $uId = Session::$user['userId'];
        $qId = $param->qId;
        $uType = $param->uType;

        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        if ($uType == 1) {
            $uModel = M("quan_user");
            $result = $uModel->where("qid=$qId and uid=$uId")->find();
        } else {
            $uModel = M("miyouquan");
            $result = $uModel->field("coins as miCoins")->where("id=$qId")->find();
        }
        $miCoins = $result["miCoins"];
        $result["miCoins"] = $miCoins;
        $result["qId"] = $qId;
        $result["uType"] = $param->uType;
        $result["endDate"] = date('Y-m-d', strtotime('+2 day'));

        Session::switchCustomer($customerId);
        Output::instance()->module('quan', "cash")->object($result);
    }

    /**
     * [saveCash 保存提现申请]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function saveCash($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        $qId = $param->qId;
        $result["qId"] = $qId;
        $type = $param->type;
        $cashNum = $param->cashNum;
        $uType = $param->uType;
        $bankAccount = $param->bankAccount;
        Session::switchCustomer(0);
        $user_role_model = M('customer_user_role');
        $role_model = M('role');
        $customerUser = M('customer_user');
        $cSettingModel = M("customer_setting");
        $uModel = M("miconis_tixian");
        $quanUserModel = M("quan_user");
        $miyouModel = M("miyouquan");
        ($type != 3) ? $bankAccount = '' : '';        //非提现到银行卡类型银行卡信息为空
        //判断可提现金额
        if ($uType == 1) {
            $result = $quanUserModel->where("qid=$qId and uid=$uId  and deleted = 0")->find();
        } else {
            $result = $miyouModel->field("coins as miCoins")->where("id=$qId")->find();
        }
        $withdrawConfig = $cSettingModel->where(['cid' => $customerId])->getField('withdrawConfig');
        $withdrawConfig = json_decode($withdrawConfig,true);
        if(empty($withdrawConfig)){
            if($cashNum < 10){
                Output::instance()->resultCode(1, "提现金额必须是大于等于10元");
                return;
            }
            $type = 1; //没有设置提现配置，默认提现到零钱并提现金额不能少于10元
        }else{
            if (!($cashNum <= $withdrawConfig['priceMax']) || !($cashNum >= $withdrawConfig['priceMin'])) {
                Output::instance()->resultCode(1, "提现金额必须是大于等于".$withdrawConfig['priceMin']."元小于等于".$withdrawConfig['priceMax']."元"   );
                return;
            }
        }


        if ($result) {
            $cash = $result["miCoins"];
            if ($cash < $cashNum) {
                Output::instance()->resultCode(1, "提现余额不足");
                return;
            }
        }
        $data = array(
            'quanId' => $qId,
            'uId' => $uId,
            'cash' => $param->cashNum,
            'balance' => $cash,
            'type' => $type,
            'state' => 0,
            'description' => '',
            'createTime' => date('Y-m-d H:i:s'),
            'bankAccount' => $bankAccount
        );
        $uModel->startTrans();
        $success = $uModel->add($data);
        if ($uType == 1) {
            $success1 = $quanUserModel->query("update wx_quan_user set miCoins=miCoins-$cashNum,totalTixian=totalTixian+$cashNum where qid=$qId and uid=$uId");
        } else {
            $success1 = $miyouModel->query("update wx_miyouquan set coins=coins-$cashNum,totalTixian=totalTixian+$cashNum where id=$qId");
        }
        if ($success !== false && $success1 !== false) {
            $uModel->commit();
            Output::instance()->resultCode(code_success);
            //发送站内消息
//            $roleId = $role_model->where(['cid' => $customerId, 'englishRole' => 'marketCenterAdmin'])->getField('id');
//            $receiveIds = $user_role_model->alias('r')
//                ->join('wx_customer_user u on u.id = r.userId')
//                ->where(['r.cid' => $customerId, 'r.roleId' => $roleId, 'u.vid' => ['exp', 'is null']])
//                ->getField('r.userId', true);//接收人id集合数组
//            $receiveIds = array_unique($receiveIds);
            $receiveIds = $customerUser->where(['customerId' => $customerId, 'agent' => 'business'])->getField('id', true);
            $quanName = $miyouModel->where(['id' => $qId])->getField('name');
            $message = '<p>营销圈：<b>' . $quanName . '</b>有新的提现申请，请前往营销圈查看，<a href = "#/joymap/marketing">前往查看</a></p>';
            PlatMessageAction::pushMessage('提现提醒', $message, $receiveIds, '', 0, 'newAllocation', '营销圈', 2, 1, 0, 0, $message, $customerId);
        } else {
            $uModel->rollback();
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }

    /**
     * [addQuanUser 主公添加密友]
     * @param [type] $param [description]
     */
    public function addQuanUser($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiQuanUserModel = M("quan_user");
        Session::switchCustomer($cid);
        $MiModel = M("user");
        $fullName = $param->fullName;
        $phone = $param->phone;
        $qId = $param->qId;

        $quanInfo = $MiQuanUserModel->query(
            "SELECT miMaxCount,(SELECT COUNT(1) FROM wx_quan_user WHERE qid=$qId AND deleted=0 AND STATUS=1) AS c FROM wx_miyouquan WHERE id=$qId"
        );

        $time = date("Y-m-d H:i:s");

        if ($quanInfo && count($quanInfo) > 0) {
//			if($quanInfo[0]["c"] >= $quanInfo[0]["miMaxCount"]) {
//				Output::instance()->resultCode(1,"密友数量超出总数限制，不能恢复");
//				return;
//			}
        }
        $rs = $MiModel->alias("a")
            ->join("left join wx_" . $cid . "_user_weixin_info b on b.id=a.weixinUserId")
            ->field("a.id,a.phone,a.fullName,b.headimgurl,b.nickname")
            ->where("a.phone='$phone'")->find();
        if ($rs && count($rs) > 0) {
            $uid = $rs["id"];
        }
        $miquanwhere["qid"] = $qId;
        $miquanwhere["uid"] = $uid;
        $miquanres = $MiQuanUserModel->where($miquanwhere)->find();
        if ($miquanres && count($miquanres) > 0) {
            Output::instance()->resultCode(1, '圈内已存在该密友！');
            return;
        } else {
            $MiModel->startTrans();
            if ($rs && count($rs) > 0) {
                $uid = $rs["id"];
            } else {
                $data["fullName"] = $fullName;
                $data["phone"] = $phone;
                $uid = $MiModel->add($data);
            }
            $quaUserData["qid"] = $qId;
            $quaUserData["uid"] = $uid;
            $quaUserData["name"] = $param->fullName;
            $quaUserData["identity"] = 1;
            $quaUserData["createTime"] = $time;
            $quaUserData["updateTime"] = $time;
            $quaUserData["status"] = 1;
            $quanUserResult = $MiQuanUserModel->add($quaUserData);

            if ($uid !== false && $quanUserResult !== false) {
                $MiModel->commit();
                Output::instance()->resultCode(code_success);
            } else {
                $MiModel->rollback();
                Output::instance()->resultCode(code_sql_error);
            }
        }
    }

    /**
     * [delQuanUser 停用密友]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function changeQuanUserDeleted($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $qId = $param->qId;
        Session::switchCustomer(0);
        $MiQuanUserModel = M("quan_user");
        if ($param->deleted == 0) { //恢复密友之前先判断是否有名额可以恢复
            $quanInfo = $MiQuanUserModel->alias("a")
                ->join("wx_miyouquan b ON a.qid=b.id")
                ->field("COUNT(1) AS c,qid,miMaxCount")
                ->where("a.qid=$qId and a.deleted=0 AND a.STATUS=1")->find();
//			if($quanInfo && $quanInfo["c"] >= $quanInfo["miMaxCount"]){
//				Output::instance()->resultCode(1,"密友数量超出总数限制，不能恢复");
//				return;
//			}
        }
        $where["id"] = array('eq', $param->id);
        $quaUserData["deleted"] = $param->deleted;
        $quaUserData["updateTime"] = date("Y-m-d H:i:s");
        $result = $MiQuanUserModel->where($where)->save($quaUserData);

        Session::switchCustomer($cid);
        if ($result !== false) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * [auditQuanUser 主公审核密友]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function auditQuanUser($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiQuanUserModel = M("quan_user");
        $MiMallUserModel = M("mimall_user");
        $orderModel = M("module_product_order");
        Session::switchCustomer($cid);
        $id = $param->id;
        $qId = $param->qid;
        $where["id"] = array('eq', $id);
        $status = $param->status;
        $price = $param->price;
        $salePrice = $param->salePrice;
        $quaUserData["status"] = $status;
        $quaUserData["joinPrice"] = $price;

        $userId = $MiQuanUserModel->where(['id' => $id])->getField('uid');
        if ($status) self::registerPoint($userId, $qId);



        $quanInfo = $MiQuanUserModel->query(
            "SELECT miMaxCount,(SELECT COUNT(1) FROM wx_quan_user WHERE qid=$qId AND deleted=0 AND STATUS=1) AS c FROM wx_miyouquan WHERE id=$qId"
        );

        if ($quanInfo && count($quanInfo) > 0) {
//			if($quanInfo[0]["c"] >= $quanInfo[0]["miMaxCount"]) {
//				Output::instance()->resultCode(1,"密友数量超出总数限制，不能恢复");
//				return;
//			}
        }

        $userInfo = $MiQuanUserModel->alias("a")
            ->join("inner join wx_" . $cid . "_user b on a.uid=b.id ")
            ->join("inner join wx_miyouquan c on c.id=a.qid ")
            ->where("a.id=$id")->find();

        if($userInfo['joinQualType'] == 2){
            $serialNumber = self::createOrderSerialNumber($userInfo['oid'], $cid);
            $data['payTime']  = $data['deliveryTime'] = date("Y-m-d H:i:s");
            $data['status'] = order_status_delivering;
            $data['tempSerialNumber'] = $serialNumber;
            $data['serialNumber'] = $serialNumber;
            $orderRes = $orderModel->where(['id' => $userInfo['oid']])->save($data);
            if(!is_numeric($orderRes)){
                Output::instance()->resultCode(code_sql_error);
                return;
            }
        }
//        $result = self::createAuditOrder($userInfo['uid'],$qId,$price,$salePrice);
//        if(!$result){
//            Output::instance()->resultCode(code_sql_error);
//            exit;
//        }
        $quanUserResult = $MiQuanUserModel->where($where)->save($quaUserData);
        if ($userInfo) {
            self::newUserMessage($qId, $userInfo['uid']);
            /*$phone=$userInfo["phone"];
			$miyouquanName = $userInfo["name"];
			$msg = "您加入".$miyouquanName."密友圈的申请已被通过。【密友圈】";
			self::getSmsCode($phone,$msg);*/
        }
        if ($quanUserResult !== false) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public static function createAuditOrder($id,$qId,$price,$salePrice){
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiMallUserModel = M("mimall_user");
        $OrderModel = M("module_product_order");
        $miyouquan = M('miyouquan');
        $DetailModel = M("module_product_order_detail");
        Session::switchCustomer($cid);
        $UserModel = M("user");

        $miUserInfo = $MiMallUserModel->where(['uId' => $id, 'qId' => $qId])->find();
        $UserInfo = $UserModel->where(['id' => $id])->find();
        $data = array(
            'fullName' => $UserInfo['fullName'],
            'phone' => $UserInfo['phone'],
            'province' => $UserInfo['province'],
            'city' => $UserInfo['city'],
            'country' => $UserInfo['country'],
            'address' => $UserInfo['address'],
            'fromUserName' => $UserInfo['userName'],
            'fromCustomerId' => $cid,
            'type' => 'joinQuan',
            'points' => '',
            'status' => order_status_delivered,
            'createTime' => date("Y-m-d H:i:s"),
            'qId' => $qId,
            'uId' => $id,
            'distributionId'=>'',
            'proSource'=>'',
            /*'miUid' => $miUId,
            'refereeUid'=>$refereeInfo['refereeUid'],
            'parentRefereeUid'=>$refereeInfo['parentRefereeUid'],*/
            'saleSource'=>$miUserInfo['saleSource'],
            'module' => '',
            'method' => '',
            'moduleId' => '',
            'IDName'=>'',
            'IDNumber'=>'',
            'miAward' => '',
            'lordAward' => '',
            'refueMoney' => 0,
            'updateTime' => date("Y-m-d H:i:s"),
            'recommenderId' => $miUserInfo['recommenderId'],
            'price' => $price
        );
        $quan=$miyouquan->where('id=' . $qId)->find();
        if($quan['onlyCutReferee']){
            $data['miUid'] = $miUserInfo['refereeUid'];
        }else{
            if($quan['cutRank'] == 3){
                $data['miUid'] = $miUserInfo['miUId'];
                $data['refereeUid'] = $miUserInfo['refereeUid'];
                $data['parentRefereeUid'] = $miUserInfo['parentRefereeUid'];
            }
            if($quan['cutRank'] == 2){
                $data['miUid'] = $miUserInfo['miUid'];
                $data['refereeUid'] = $miUserInfo['refereeUid'];
            }
            if($quan['cutRank'] == 1){
                $data['miUid'] = $miUserInfo['miUId'];
            }
        }
        $result = $dataDetail["oid"] = $OrderModel->add($data);

        $tempSerialNumber = self::createOrderSerialNumber($id, $cid);
        $OrderModel->where(['id' =>$result])->setField('tempSerialNumber', $tempSerialNumber);

        $quanInfo = $miyouquan->where("id=$qId")->find();
        $miAward = $quanInfo['miAward'];
        $refereeAward = $quanInfo['refereeAward'];
        $parentRefereeAward = $quanInfo['parentRefereeAward'];
        $lordAward = 1;
        $dataDetail["userId"] = $id;
        $dataDetail["fromUserName"] = $UserInfo['userName'];
        $dataDetail["price"] =$price;
        $dataDetail['qId']=$qId;
        $dataDetail["saleCut"]=$salePrice;
        if($qId&&$miUserInfo['miUid']){
            $dataDetail['miUserRatio']=$miAward;
            $dataDetail['isMiUserCut']=$salePrice*$miAward;
            $lordAward-=$miAward;
        }
        if($qId&&$miUserInfo['refereeUid']){
            $dataDetail['refereeRatio']=$refereeAward;
            $dataDetail['isRefereeCut']=$salePrice*$refereeAward;
            $lordAward-=$refereeAward;
        }
        if($qId&&$miUserInfo['parentRefereeUid']){
            $dataDetail['parentRefereeRatio']=$parentRefereeAward;
            $dataDetail['isParentRefereeCut']=$salePrice*$parentRefereeAward;
            $lordAward-=$parentRefereeAward;
        }
        if($qId&&$miUserInfo['miUId']){
            $dataDetail['lordRatio']=$lordAward;
            $dataDetail['isLordCut']=$salePrice*$lordAward;
        }
        $resultTemp = $DetailModel->add($dataDetail);
        if($resultTemp && $result){
            return true;
        }else{
            return false;
        }


    }
    //商品编号使用客户id + 时间 + id后三位
    private static function createOrderSerialNumber($ids, $customerId) {
        if (!strstr($ids, ',')) {
            $id = $ids;
        } else {
            // 如果拆单则使用第一个订单的id
            $id = substr($ids,0,strpos($ids,','));
        }

        $length = strlen($id);
        if ($length >= 3) {
            $id = substr($id, -3);
        } else {
            $id = str_pad($id, 3, '0', STR_PAD_LEFT);
        }
        $sn = $customerId . date("ymdHis") . $id;
        return $sn;
    }

    /**
     * 好友加入密友圈,发送模板消息
     * @param $qid
     * @param $uid
     * @return bool
     */
    private static function newUserMessage($qid, $uid)
    {
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $quanUser = M("quan_user");
        $miyouquan = M("miyouquan");
        $mimallUser = M("mimall_user");
        $userInfo = $quanUser->alias("a")
            ->join("wx_quan_user b on a.refereeUid = b.uid and a.qid =b.qid and b.status=1 and b.deleted=0")
            ->join("wx_".$cid."_user c on a.uid = c.id")
            ->join("wx_miyouquan d on a.qid = d.id")
            ->field("a.nickName,a.createTime,a.refereeUid,b.nickName as refNickName,b.refereeUid as parRefereeUid,a.saleSource,c.phone,d.name as qname")
            ->where("a.qid = $qid and a.uid = $uid and a.deleted = 0")
            ->find();

        $quanInfo = $miyouquan->where("id=$qid")->field('cId, name, refereeAward, parentRefereeAward')->find();
        Session::switchCustomer($quanInfo['cId']);
        $TemplateModel = M("template_messages");
        $twhere['status'] = array("eq", "makepartner");
        $templatemsg = $TemplateModel->where($twhere)->find();
        $templateId = $templatemsg['templateId'];
        $mimallWhere['cId'] = array("eq", $quanInfo['cId']);
        //$friendUrl = C("SERVER_HOST") . "call.html?customerId=".$cid."&module=community&method=index&params={'qid':$qid}#/myfans";
        $customer = WeixinApi::getCustomer();
        if($customer['mode']&&$customer['grantStatus']){
            $domainName = $customer["appid"];
            $http['RESOURCEURL']="http://".$domainName.".".C('NEWRESOURCEURL');
        }else{
            $http['RESOURCEURL'] = C("SERVER_NAME").'/';
        }
        //$http = WeixinApi::getDomainName();
        $friendUrl = $http['RESOURCEURL'] . "spa/index.html#/quan/myFrends?customerId=".$cid."&scope=60&params=%7B%22qId%22%3A".$qid.",%22community%22%3A1%7D";
        //Log::write('jie----1220'.print_r($userInfo, true));
        if ($userInfo['refereeUid'] && ($uid != $userInfo['refereeUid']) && ($quanInfo['refereeAward'] > 0)) {
            $mimallWhere['uId'] = array("eq", $userInfo['refereeUid']);
            $refereeInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
            $data['first'] = array('value' => $userInfo['nickName'] . '通过您的推荐已经加入' . $quanInfo['name'], 'color' => "#743A3A");
            $data['keyword1'] = array('value' => $userInfo["nickName"], 'color' => '#173177');
            $data['keyword2'] = array('value' => $userInfo["createTime"], 'color' => '#173177');
            $data['remark'] = array('value' => '您又多了一位好友，继续加油哦。', "color" => '#008000');
            $toUser = $refereeInfo['openid'];
            $url = urlencode($friendUrl);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url, $topcolor, $data, TRUE, $quanInfo['cId']);
        }
        if ($userInfo['parRefereeUid'] && ($uid != $userInfo['parRefereeUid']) && ($userInfo['parRefereeUid'] != $userInfo['refereeUid']) && ($quanInfo['parentRefereeAward'] > 0)) {
            $mimallWhere['uId'] = array("eq", $userInfo['parRefereeUid']);
            $parRefereeInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
            $data['first'] = array('value' => $userInfo['nickName'] . '通过您的好友' . $userInfo['refNickName'] . '推荐已经加入' . $quanInfo['name'], 'color' => "#743A3A");
            $data['keyword1'] = array('value' => $userInfo["nickName"], 'color' => '#173177');
            $data['keyword2'] = array('value' => $userInfo["createTime"], 'color' => '#173177');
            $data['remark'] = array('value' => '您又多了一位好友，继续加油哦。', "color" => '#008000');
            $toUser = $parRefereeInfo['openid'];
            $url = urlencode($friendUrl);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url, $topcolor, $data, TRUE, $quanInfo['cId']);
        }
        if ($userInfo['saleSource'] && ($uid != $userInfo['saleSource'])) {
            $mimallWhere['uId'] = array("eq", $userInfo['saleSource']);
            $parRefereeInfo = $mimallUser->where($mimallWhere)->field("openid")->find();
            $data['first'] = array('value' => $userInfo['nickName'] . '通过您的客户' . $userInfo['refNickName'] . '推荐已经加入' . $quanInfo['name'], 'color' => "#743A3A");
            $data['keyword1'] = array('value' => $userInfo["nickName"], 'color' => '#173177');
            $data['keyword2'] = array('value' => $userInfo["createTime"], 'color' => '#173177');
            $data['remark'] = array('value' => '您又多了一个客户，继续加油哦。', "color" => '#008000');
            $toUser = $parRefereeInfo['openid'];
            $friendUrl = $http['RESOURCEURL'].'spa/index.html#/quan/customerManager?customerId='.$cid.'&params=%7B%22qId%22%3A'.$qid.'%7D';
            $url = urlencode($friendUrl);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url, $topcolor, $data, TRUE, $quanInfo['cId']);
        }

        if(!$userInfo['refereeUid']){
            $lord = $quanUser->where(['identity'=>0, 'qid'=>$qid, 'deleted'=>0])->find();
            $openid = $mimallUser->where(['uId'=>$lord['uid'],'cId'=>$cid, 'qid'=>$qid])->getField('openid');
            $data['first'] = array('value' => $userInfo['nickName'] . '已经加入' . $quanInfo['name'], 'color' => "#743A3A");
            $data['keyword1'] = array('value' => $userInfo["nickName"], 'color' => '#173177');
            $data['keyword2'] = array('value' => $userInfo["createTime"], 'color' => '#173177');
            $data['remark'] = array('value' => '您又多了一个客户，点击查看详情。', "color" => '#008000');
            $toUser = $openid;
            $friendUrl = $http['RESOURCEURL'].'/spa/index.html#/quan/frendsManager?customerId='.$cid.'&scope=60&params=%7B%22qId%22%3A'.$qid.'%7D';
            $url = urlencode($friendUrl);
            $topcolor = "#FF0000";
            WeixinApi::sendTpl($toUser, $templateId, $url, $topcolor, $data, TRUE, $quanInfo['cId']);
        }
        //20180723mh增加短信发送
        if ($userInfo['phone']) {
            $templateParam['qname'] = $userInfo['qname'];
            $params = new stdClass();
            $params->phone = $userInfo['phone'];
            $params->module = 'marketing' ;
            $params->status = 'join' ;
            $params->message = "恭喜您成功加入".$userInfo['qname']."，成为注册好友";
            $params->templateParam = json_encode($templateParam);
            Module::callModule('phone', NULL, 'sendSms', $params);
        }
//		Session::switchCustomer($cid);
        return true;
    }

    public function getMiContentList($qId, $order, $start, $limit)
    {
        Session::switchCustomer(0);
        $customerId = Session::$user['customerId'];
        $vendorModel = M("micontent");
        Session::switchCustomer($customerId);
        $pageStart = $start * $limit;
        $where["qv.quanId"] = array('eq', $qId);
        $where["wmc.deleted"] = array('eq', 0);

        $timegroup = $vendorModel->query(
            "SELECT DATE_FORMAT(b.publishTime,'%Y/%m/%d') AS miniday,GROUP_CONCAT(b.id) AS ids"
            . " FROM wx_miyouquan a INNER JOIN wx_micontent b ON a.vid=b.vId WHERE a.id=$qId and b.deleted=0"
            . " GROUP BY miniday ORDER BY miniday DESC LIMIT $pageStart,$limit "
        );
        //按天分组循环
        foreach ($timegroup as $key => $val) {
            $ids = $val["ids"];
            $result = $vendorModel->query(
                "SELECT * FROM (SELECT b.id,b.picUrl,b.title,b.createTime,b.publishTime,b.recomment FROM wx_miyouquan a"
                . " INNER JOIN wx_micontent b ON a.vid=b.vId WHERE a.id=$qId AND b.deleted=0 ) c WHERE c.id IN ($ids) ORDER BY c.publishTime DESC"
            );
            $timegroup[$key]["list"] = $result;
        }
        $total = $vendorModel->query(
            "select count(1) as t from (SELECT DATE_FORMAT(b.publishTime,'%Y-%m-%d') AS miniday"
            . " FROM wx_miyouquan a INNER JOIN wx_micontent b ON a.vid=b.vId WHERE a.id=$qId and b.deleted=0 GROUP BY miniday) as c"
        );
        $out = new StdClass();
        if ($total && count($total) > 0) {
            $out->count = $total[0]["t"];
        }
        $out->pageCount = getPageCount($count, $limit);
        $out->list = $timegroup;
        Output::instance()->object($out);
    }

    /**密友圈到商家的中间跳转页面*/
    public function goToCustomer($param)
    {
        $method = $param->method;
        $module = $param->module;
        $customerId = $param->customerId;
        $newP = new StdClass();
        $newP->qId = $param->qId;
        $newP->fromGuid = $param->fromGuid;
        $newP->id = $param->pid;
        $newP->miUId = $param->miUId;
        $newP->fromUserName = $param->userName;
        $newP->oid = $param->oid;
        if ($module == "tuan") {
            $newP->teamId = $param->teamId;;
        }
        if ($module == "micontent") {
            $newP->id = $param->contentId;
        }
        if ($param->tagId) {
            $newP->tagId = $param->tagId;
        }
        if ($param->tplid) {
            $newP->tplid = $param->tplid;
        }
        $periodId = $param->periodId;
        if ($periodId) {
            $newP->periodId = $periodId;
            $newP->fromOpenId = $param->fromOpenId;
        }
        $newP = urlencode(json_encode($newP));
        $url = C("SERVER_HOST") . "call.html?customerId=$customerId&module=$module&method=$method&params=$newP";
        redirect($url);
    }

    /**
     * [auth 密友停用以后页面控制]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function auth($param)
    {
        Output::instance()->module('quan', "auth")->object($param);
    }

    /**
     * 密友招募
     */
    public function getMienlistPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $qId = $param->qId;
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $MiModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $result = $MiModel->where("id=$qId")->find();
        if ($result) {
            $result["qId"] = $qId;
            Output::instance()->module('quan', "mienlist")->object($result);
        } else {
            Output::instance()->resultCode(1, "密友圈不存在！");
        }
    }

    /**
     * 推广页面
     */
    public function getMiendetailPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $qId = $param->qId;
        $id = $param->id;
        $uid = Session::$user['uid'];
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $MiQuanModel = M("quan_user");
        $quanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        if ($id) {
            $customerId = Session::$user['customerId'];
            $articleModel = M("web_page");
            $result = $articleModel->where("id=$id")->find();
        }

        $miInfo = $MiQuanModel->alias("a")
            ->join("inner join wx_miyouquan b on a.qId=b.id")
            ->field("a.nickName,a.headImgUrl,a.id as quanUserId,b.*")
            ->where("qId=$qId and uid=$uid")
            ->find();
        $result["qId"] = $qId;
        $result["id"] = $id;
        $result["qrCodeImg"] = $miInfo["qrCodeImg"];
        $result["headImgUrl"] = $miInfo["headImgUrl"];
        $result["nickName"] = $miInfo["nickName"];
        $miInfo["customerId"] = $customerId;
        $result["fromUId"] = $uid;
        $miInfo["uid"] = $uid;
        if (!$result["qrCodeImg"]) {
            $out = self::createImage($miInfo);
            if ($out && !$out->code) {
                $result["qrCodeImg"] = $out->path;
                $updateData["qrCodeImg"] = $out->path;
                $quanModel->where("id=$qId")->save($updateData);
            } else {
                Output::instance()->resultCode(1, $out->msg);
                return;
            }
        }
        $result["date"] = date('YmdHis');
        if ($result) {
            Output::instance()->module('quan', "miendetail")->object($result);
        } else {
            Output::instance()->resultCode(1, '文章不存在');
        }
    }

    /**
     * 好友加入圈子最终入口
     * @param $params
     */
    public function subscribeRegQuanUser($params)
    {
        Log::write('subscribeRegQuanUser-params:'.serialize($params));
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        $user_role_model = M('customer_user_role');
        $role_model = M('role');
        $MiQuanUserModel = M("quan_user");
        $MiUStatisticsModel = M("miu_statistics");
        $white_tab = M('rank_white_list');
        $miyouquanModel = M("miyouquan");
        $mimallModel = M("mimall_user");
        Session::switchCustomer($cid);
        $user = M("user");
        $weixinUserModel = M("user_weixin_info");
        $userName = $params->userName;
        $qId = $params->id;
        $uid = $params->uid;
        $backend = $params->backend;
        $recommenderId = $params->recommenderId;
        if ($backend == 1) {
            $qId = $params->qId;
        }
        $wxId = $params->wxId;
        $signSaleSource = $params->signSaleSource;
        if (!$qId) {
            $qId = C("DETAULT_QUANID");
        }
        $userWeixinResult = $weixinUserModel->where("openid='" . $userName . "'")->find();
        $time = date("Y-m-d H:i:s");
        if($userName){
            $rs = M()->table('wx_' . $cid . '_user')->where("userName='".$userName."'")->find();
        }else{
            $rs = M()->table('wx_' . $cid . '_user')->where("id=$uid")->find();
        }
        if ($userWeixinResult == null || $rs == null) {
            Log::write('user_weixin_info表-userId:'.$rs["id"].'|sql:'.$weixinUserModel->getLastSql().'|count:'.count($userWeixinResult));
            Log::write('user表'.M()->getLastSql().'|count:'.count($rs));
        }
        if ($rs && count($rs) > 0) {
            $uid = $rs["id"];
        }
        if (!$uid) {
            return;
        }

        //同一商城内加入了其他圈也不处理
        $miquanwhere["uid"] = array("eq", $uid);
        $miquanwhere["qid"] = array("eq", $qId);
        $miquanwhere["deleted"] = array("eq", 0);
        $miquanres = $MiQuanUserModel->where($miquanwhere)->find(); //如果已经这个圈了，不处理
        $miyouquan = $miyouquanModel->where("id=" . $qId)->find();
        if ($miquanres && count($miquanres) > 0) {
//			$upData["deleted"]="0";
//			$qid=$miquanres["id"];
//		    $MiQuanUserModel->where("id=$qid")->save($upData);
            $out = new stdClass();
            $out->code = 0;
            $out->qId = $miquanres["qid"];
            return;
        } else {

            $user->startTrans();
            $quaUserData["qid"] = $qId;
            $quaUserData["uid"] = $uid;
            $quaUserData["name"] = $params->fullName;
            $quaUserData["identity"] = 1;
            $quaUserData["createTime"] = $time;
            $quaUserData["activeTime"] = $time;
            $quaUserData["updateTime"] = $time;
            $quaUserData["wxId"] = $wxId;
            $quaUserData["friendCount"] = 0;
            $quaUserData["oid"] = $params->oid;
            $quaUserData["rankId"] = $params->rankId;
            if ($miyouquan["joinType"] == 1) {
                $quaUserData["status"] = 0;
            } else {
                $quaUserData["status"] = 1;
            }
            $mimallWhere["uId"] = array("eq", $uid);
            $mimallWhere["qId"] = array("eq", $qId);
            if ($params->miUId) {
                if (($params->miUId != $uid)) {
                    $quaUserData["refereeUid"] = $params->miUId;
                }
            } else {
                $mimallWhere["miUid"] = array("neq", $uid);
                $mimallInfo = $mimallModel->where($mimallWhere)->find();
                unset($mimallWhere["miUid"]);
                Log::write("通过锁定查找推荐人  " . $mimallModel->getLastSql() . "---" . $mimallInfo['miUid']);
                $quaUserData["refereeUid"] = $mimallInfo['miUid'];
            }
            if ($userWeixinResult) {
                $quaUserData["nickName"] = $userWeixinResult["nickname"];
                $quaUserData["headImgUrl"] = $userWeixinResult["headimgurl"];
            }
            if ($signSaleSource) {
                $quaUserData['isSaleSource'] = 1;
                $quaUserData['saleSource'] = $uid;
                $quaUserData["refereeUid"] = null;
            } else {
                if ($quaUserData["refereeUid"]) {
                    $refereeWhere["qid"] = $qId;
                    $refereeWhere["uid"] = $quaUserData["refereeUid"];
                    $refereeWhere["deleted"] = 0;
                    $refereeInfo = $MiQuanUserModel->where($refereeWhere)->find();
                    if ($refereeInfo['saleSource']) {
                        $quaUserData['saleSource'] = $refereeInfo['saleSource'];
                    }
                }
            }
            $mimallData['miUid'] = $uid;
            $mimallData['qId'] = $qId;
            $mimallData['saleSource'] = $quaUserData['saleSource'];
            $mimallData['refereeUid'] = $quaUserData["refereeUid"];
            //mh修改三级好友存法
            if (!empty($mimallData['refereeUid'])) {
                $mimallData['preRefereeUid'] = $MiQuanUserModel->where(['qid' => $qId, 'uid' => $mimallData['refereeUid'],'deleted' => 0])->getField('refereeUid');
                // if (!empty($mimallData['refereeUid'])) {
                //     $mimallData['preRefereeUid'] = $MiQuanUserModel->where(['qid' => $qId, 'uid' => $mimallData['refereeUid'],'deleted' => 0])->getField('refereeUid');
                // }
            }
            unset($mimallWhere["qId"]);
            $mimallWhere["cId"] = array("eq", $cid);
            $isDelete = 0;
            if($signSaleSource){//如果是销售,将不存在推荐人信息
                $mimallData['refereeUid'] = null;
                $mimallData['preRefereeUid'] = null;
                $mimallData['saleSource'] = $uid;
            }
            /** 判断是否需要统计
             * 1.  $params->statis = 1 表示在callAction刚刚加入mimall_user加入时只是普通好友,给他的上级人员已经加了普通好友数                    量,以下方法更换他的身份变为注册好友,需要把刚刚加入mimall_user加入时给他的上级人员已经加了普通好友数量进行
                    扣除,更改为新身份后再次进行统计
                2. $isStatis > 0  表示此次加入圈的人原来加入过该cid下的哪一个营销圈并且删除了,删除时给他的上级人员扣除注册好友                   数量和普通好友数量,并且变为普通好友时给他的上级人员加了普通好友数
             */
            $isStatis = $MiQuanUserModel->alias('user')->join('wx_miyouquan as quan on quan.id=user.qid')->where(['quan.cId' => $cid, 'user.uid' => $uid, 'user.deleted' => 1])->count();
//            if($params->statis == 1 || $isStatis > 0){
//                $isDelete = 1;
//            }

            if ($mimallModel->where($mimallWhere)->find()) {
//                R("StatisTics/miMallUserSave", array($mimallWhere, $mimallData, $cid, $isDelete));
                $mimallModel->where($mimallWhere)->save($mimallData);             //LP修改  添加由StatisTics/miMallUserSave方法执行
            } else {
                /*jie,新增保存mimalluser信息*/
                $openid = $user->where(['id' => $uid])->getField('userName');
                $mimallData['fromModule'] = 'quan';
                $mimallData['openid'] = $openid;
                $mimallData['cId'] = $cid;
                $mimallData['uId'] = $uid;
                $mimallData['createTime'] = date('Y-m-d H:i:s');
                $mimallData['recommenderId'] = $recommenderId;
//                R("StatisTics/miMallUserSave", array('', $mimallData, $cid));
                $mimallModel->add($mimallData);                                   //LP修改  修改由StatisTics/miMallUserSave方法执行
            }

//            $mimallModel->where(['recommendManUid' => $uid])->save(['miUid' => $uid]);

            $quanUserResult = $MiQuanUserModel->add($quaUserData);
            if($params->rankId && $rs['phone']){
                $whiteWhere['rankId'] = $params->rankId;
                $whiteWhere['phone'] = $rs['phone'];
                $whiteData['status'] = 1;
                $whiteData['uid'] = $uid;
                $whiteData['updateTime'] = date('Y-m-d H:i:s');;
                $white_tab->where($whiteWhere)->save($whiteData);
                Log::write('白名单已使用'.$rs['phone'].$white_tab->getLastSql());
            }
            if ($quaUserData["status"]) self::registerPoint($quaUserData['uid'], $qId); //给予注册积分
            $mallId = $mimallModel->where($mimallWhere)->getField('id');
//            R("StatisTics/friendsNumber", array($mallId, $cid));


            if ($uid !== false && $quanUserResult !== false) {
                if ($miyouquan["joinType"] == 1 && (!$miyouquan["joinPid"])) {
                    /*$master = $MiQuanUserModel->alias("a")
                        ->join("inner join wx_".$cid."_user c on c.id = a.uid")
                        ->field("c.phone")
                        ->where("a.qid=".$qId." and a.identity = 0")
                        ->find();
                    if($rs["fullName"]){
                        $msg = $rs["fullName"]."申请加入您的密友圈，请尽快审核。【密友圈】";
                    }else{
                        $msg = $userWeixinResult["nickname"]."申请加入您的密友圈，请尽快审核。【密友圈】";
                    }
                    if($master["phone"]){
                        self::getSmsCode($master["phone"],$msg);
                    }*/
                }
                $user->commit();
            } else {
                $user->rollback();
            }
            if ($quaUserData['status'] == 1) {
                self::newUserMessage($qId, $uid);
//                $roleId = $role_model->where(['cid' => $cid, 'englishRole' => 'marketCenterAdmin'])->getField('id');
//                $receiveIds = $user_role_model->alias('r')
//                    ->join('wx_customer_user u on u.id = r.userId')
//                    ->where(['r.cid' => $cid, 'r.roleId' => $roleId, 'u.vid' => ['exp', 'is null']])
//                    ->getField('r.userId', true);//接收人id集合数组
//                $receiveIds = array_unique($receiveIds);
                $receiveIds = $customerUser->where(['customerId' => $cid, 'agent' => 'business'])->getField('id', true);
                $message = '<p>营销圈：<b>' . $miyouquan['name'] . '</b>有新的成员加入，请前往营销圈查看，<a href = "#/joymap/marketing">前往查看</a></p>';
                PlatMessageAction::pushMessage('营销圈新成员提醒', $message, $receiveIds, '', 0, 'newAllocation', '营销圈', 2, 1, 0, 0, $message, $cid);
            } elseif ($quaUserData['status'] == 0) {
//                $roleId = $role_model->where(['cid' => $cid, 'englishRole' => 'marketCenterAdmin'])->getField('id');
//                $receiveIds = $user_role_model->alias('r')
//                    ->join('wx_customer_user u on u.id = r.userId')
//                    ->where(['r.cid' => $cid, 'r.roleId' => $roleId, 'u.vid' => ['exp', 'is null']])
//                    ->getField('r.userId', true);//接收人id集合数组
//                $receiveIds = array_unique($receiveIds);
                $receiveIds = $customerUser->where(['customerId' => $cid, 'agent' => 'business'])->getField('id', true);
                $message = '<p>营销圈：<b>' . $miyouquan['name'] . '</b>有新的成员待审核，请前往营销圈查看，<a href = "#/joymap/marketing">前往查看</a></p>';
                PlatMessageAction::pushMessage('营销圈新成员审核提醒', $message, $receiveIds, '', 0, 'newAllocation', '营销圈', 2, 1, 0, 0, $message, $cid);
            }
        }
    }

    /**给予注册积分
     * @param $userId
     * @param $qId
     */
    private function registerPoint($userId, $qId)
    {
        Log::write('quanaddhoujia' . $userId . '---' . $qId);
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mimallUserModel = M('mimall_user');
        Session::switchCustomer($customerId);
        $InviteRewardModel = D('InviteReward', 'Logic');
        $pointModel = D('Point', 'Logic');
        $points = $InviteRewardModel->getInvitePoint();
        $data = $mimallUserModel->where(['uId' => $userId, 'qId' => $qId, 'cId' => $customerId])->find();

        foreach ($points as $point) {
            $pointConfig = [
                'userId' => $data['uId'],
                'miUid' => $data['miUid'],
                'refereeUid' => $data['refereeUid'],
                'preRefereeUid' => $data['preRefereeUid'],
                'recommenderId' => $data['recommenderId'],
                'registerUserPoint' => $point['registerUserPoint'],
                'registerMiPoint' => $point['registerMiPoint'],
                'registerPreMiPoint' => $point['registerPreMiPoint'],
                'registerPrePreMiPoint' => $point['registerPrePreMiPoint'],
                'registerRecommenderPoint' => $point['registerRecommenderPoint'],
                'pointSchemeId' => $point['pointSchemeId'],
                'pointSchemeName' => $point['pointSchemeName']
            ];
            if (!$point['noInviteRegisterReward'] && !$pointConfig['recommenderId']) $pointConfig['registerUserPoint'] = 0;//非邀请情况不得积分

            /*添加邀请记录*/
            $recordId = $InviteRewardModel->addInviteRecord(
                $data['uId'],
                $point['inviteRewardId'],
                $data['refereeUid'],
                2,
                null,
                0,
                null,
                1,
                $point['registerUserPoint'],
                json_encode($pointConfig),
                'quan',
                $data['qId']
            );

            /*给予注册积分*/
            if (!empty($pointConfig['registerUserPoint']) && $pointConfig['userId']) { //给注册人加积分
                $pointModel->addPoint(
                    $pointConfig['userId'],
                    $pointConfig['registerUserPoint'],
                    'register',
                    $recordId,
                    '加入营销圈',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['registerPreMiPoint']) && $pointConfig['refereeUid']) { //给注册好友推荐人积分
                $pointModel->addPoint(
                    $pointConfig['refereeUid'],
                    $pointConfig['registerPreMiPoint'],
                    'register',
                    $recordId,
                    '邀请好友加入营销圈',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['registerPrePreMiPoint']) && $pointConfig['preRefereeUid']) { //给注册好友上级推荐人积分
                $pointModel->addPoint(
                    $pointConfig['preRefereeUid'],
                    $pointConfig['registerPrePreMiPoint'],
                    'register',
                    $recordId,
                    '好友邀请营销圈新用户',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['registerRecommenderPoint']) && $pointConfig['recommenderId']) { //给推荐好友积分
                $pointModel->addPoint(
                    $pointConfig['recommenderId'],
                    $pointConfig['registerRecommenderPoint'],
                    'register',
                    $recordId,
                    '邀请好友加入营销圈',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }
        }
    }

    public function curls($url, $timeout = '10')
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 3. 执行并获取HTML文档内容
        $info = curl_exec($ch);
        // 4. 释放curl句柄
        curl_close($ch);

        return $info;
    }

    public function createImage($miInfo)
    {
        $quanUserId = $miInfo["quanUserId"];
        $customerId = $miInfo["customerId"];
        $uid = $miInfo["uid"];
        $qId = $miInfo["id"];
        $regUrl = C("SERVER_HOST") . "call.html?customerId=$customerId&module=quan&method=mireg&scope=1&params=%7B%22qId%22%3A%22$qId%22%2C%22fromUId%22%3A%22$uid%22%7D";
        $bgImgUrl = $miInfo["bgImgUrl"];
        $headImgUrl = $miInfo["headImgUrl"];
        $fname = "QrCodeImg_$quanUserId.png";
        if (!$bgImgUrl) {
            $bgImgUrl = C("DEFAULT_BGIMG");
        }
        $fileName = LOCAL_PIC_PATH . "/$fname";
        $qrCodeName = LOCAL_PIC_PATH . "/$quanUserId.png";

        $img = imagecreatefromstring(self::curls($bgImgUrl));
        $imgWidth = imagesx($img);
        //PhpQRcode::png($regUrl, $qrCodeName, 'L', 9,4);
        //调用微信二维码生成工具生成二维码
        $params["qId"] = $qId;
        $data = QRCode::add(
            "密友圈推广注册二维码",
            "QRCODE_" . $customerId . "_" . $quanUserId . "_" . $qId,
            "quan", $qId, "subscribeRegQuanUser",
            "QR_LIMIT_STR_SCENE"
        );
        $qrCodeName = $data["img"];
        if (!$img) {
            Log::write('背景图片获取错误');
            $out1 = new stdClass();
            $out1->code = 1;
            $out1->msg = "背景图片获取错误，请重试";
            return $out1;
        }

        $headImg = self::curls($headImgUrl);
        $headImg = imagecreatefromstring($headImg);
        $headImgWidth = imagesx($headImg);
        $headImgHeight = imagesy($headImg);
        $out1 = new StdClass();
        if (!$headImg) {
            Log::write('头像获取错误');
            $out1->code = 1;
            $out1->msg = "头像获取错误，请重试";
            return $out1;
        }
        $qrImg = self::curls($qrCodeName);

        $qrImg = imagecreatefromstring($qrImg);
        $qrImgWidth = imagesx($qrImg);
        $qrImgHeight = imagesy($qrImg);
        $qrImgLeft = ($imgWidth - 240) / 2;

        if (!$qrImg) {
            Log::write('二维码生成错误');
            $out1->code = 1;
            $out1->msg = "二维码生成错误，请重试";
            return $out1;
        }
        // if (file_exists($qrCodeName)) {
        //               @unlink ($qrCodeName);
        //       }
        $fontcolor = imagecolorallocate($img, 46, 46, 46);
        $fontcolor1 = imagecolorallocate($img, 209, 19, 119);
        $font = __DIR__ . "/FZLTHJW.TTF";

        $fontsize = 18;
        imagettftext($img, $fontsize, 0, 150, 60, $fontcolor, $font, "我是");
        imagettftext($img, $fontsize, 0, 200, 60, $fontcolor1, $font, $miInfo["nickName"] . ",我在密友圈。");

        imagecopyresampled($img, $headImg, 20, 40, 0, 0, 110, 110, $headImgWidth, $headImgHeight);

        imagecopyresampled($img, $qrImg, $qrImgLeft, 470, 0, 0, 200, 200, $qrImgWidth, $qrImgHeight);
        imagejpeg($img, $fileName);
        imagedestroy($img);
        imagedestroy($headImg);

        //开始上传
        if ($headImg && $qrImg) {
            if (file_exists($fileName)) {
                $out = R("Upload/uploadLocalFileToOss", array($fname, $fileName));
                if (!$out->code) {
                    return $out;
                }
            }
        } else {
            $out = new StdClass();
            $out->code = 1;
        }
    }

    public function getMiregPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $qId = $param->qId;
        if (!$qId) { //如果注册页面从菜单进入或者从消息中进入
            $qId = C("DETAULT_QUANID");
        }
        $id = $param->id;
        $uid = Session::$user['uid'];
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $MiQuanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $distribution = M("module_distribution_scheme");
        if ($id) {
            $customerId = Session::$user['customerId'];
            $articleModel = M("web_page");
            $result = $articleModel->where("id=$id")->find();
        }
        $miInfo = $MiQuanModel->alias("a")
            ->join("left join wx_module_product b on a.joinPid=b.id")
            ->join("left join wx_mishare c on b.id=c.moduleId and c.module='product'")
            ->field("a.*,c.id as sId,b.vId,b.fromCustomerId,b.distributionId,b.proSource")
            ->where("a.id=$qId")->find();
        if (!$miInfo['distributionId']) {
            $distriWhere['isDefault'] = array('eq', 1);
            $distriWhere['deleted'] = array('eq', 0);
            $distributionInfo = $distribution->where($distriWhere)->field('id')->find();
            $miInfo['distributionId'] = $distributionInfo['id'];
        }

        if (self::joinQualifications($qId)) {
            $miInfo['satisfy'] = 1;
        } else {
            $miInfo['satisfy'] = 0;
        }

        $miInfo["joinPid"] ? $miInfo["payJoin"] = 1 : $miInfo["payJoin"] = 0;
        $miInfo["qId"] = $qId;
        $miInfo["fromUId"] = $uid;
        $miInfo["uid"] = $uid;
        $miInfo["examine"] = $param->examine;
        Output::instance()->module("quan", "mireg")->object($miInfo);
    }

    private static function joinQualifications($qid)
    {
        $customerId = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $MiQuanModel = M("miyouquan");
        $mimall = M("mimall_user");
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $quanInfo = $MiQuanModel->alias("a")
            ->join("wx_mimall b on a.mallId=b.id")
            ->field("a.json,b.fromCustomerId")
            ->where("a.id=$qid")
            ->find();
        $selfInfo = $mimall->where("qId = $qid and uId = $uid and cId=" . $quanInfo['fromCustomerId'])->field("openid")->find();
        $userName = $selfInfo['openid'];
        $orderWhere['fromUserName'] = array('eq', $userName);
        $orderWhere['wxTransactionId'] = array("neq", "");
        $orderWhere['status'] = array(array('neq', 'refund'), array('neq', 'refundedpart'), array('neq', 'refunding'), 'or');
        $json = json_decode($quanInfo['json'], true);
        if ($json['joinCondition']) {
            if ($json['joinCondition']['singleShopping']['status'] == 1) {
                $singleShopping = $json['joinCondition']['singleShopping']['condition'];
                $orderWhere['price'] = array('egt', $singleShopping);
                $result = $orderModel->where($orderWhere)->find();
                if ($result) {
                    return true;
                }
                unset($orderWhere['price']);
            }
            if ($json['joinCondition']['totalShopping']['status'] == 1) {
                $totalShopping = $json['joinCondition']['totalShopping']['condition'];
                $result = $orderModel->where($orderWhere)->field("sum(price) as price")->find();
                if ($result['price'] >= $totalShopping) {
                    return true;
                }
            }
        }
        return false;
    }

    public function verifyCode($param)
    {
        $phone = $param->phone;
        $code = $param->code;
        $out = new stdClass();
        if (!$phone) {
            $out->code = 1;
            $out->msg = "手机号不能为空！";
            Output::instance()->object($out);
            return;
        }
        $sessionCode = session("smsCode");
        if (!$sessionCode && $code) {
            $out->code = 2;
            $out->msg = "验证码已过期";
            Output::instance()->object($out);
            return;
        }
        if ($code && $sessionCode != $code) {
            $out->code = 3;
            $out->msg = "验证码错误";
            Output::instance()->object($out);
            return;
        }
        session("smsCode", null);
        Output::instance()->resultCode();
    }

    /**
     * [regQuanSave 密友注册]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function regQuanSave($param)
    {
        Log::write('regQuanSave-param:'.serialize($param));
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        $userName = Session::$user['userName'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $myq_tab = M('miyouquan');
        Session::switchCustomer($cid);
        $MiModel = M("user");

        /*Session::switchCustomer(0);
        //$quanUserModel=M("quan_user");
        Session::switchCustomer($cid);
        $MiModel = M("user");*/
        $fullName = $param->fullName;
        $phone = $param->phone;
        $qid = $param->qId;
        $wxNumber = $param->wxId;
        $email = $param->email;
        $city = $param->city;
        $province = $param->province;
        $address = $param->address;
        $birthday = $param->birthday;
        $customInfo = $param->customInfo;
        $recommenderId = $param->recommenderId;
        //需要验证的手机号
        $verifyPhone = $param->verifyPhone;
        $oid = $param->oid;
        $rankId = $param->rankId;
        //mh添加手机号验证代码。20180127
        if ($verifyPhone){
            $phone_params = new StdClass();
            $phone_params->phone = $verifyPhone;
            Module::callModule('phone', NULL, 'verifyPhone', $phone_params);
            $phone = $param->verifyPhone;
            $data["isVerifyPhone"] = 1;
        }
        //--------
        
        //$time = date("Y-m-d H:i:s");

        $quaParams = new stdClass();
        $quaParams->userName = $userName;
        $quaParams->id = $qid;
        $quaParams->miUId = $param->miUId;
        $quaParams->wxId = $wxNumber;
        $quaParams->recommenderId = $recommenderId;
        $quaParams->oid = $oid;
//        $quaParams->statis = $param->statis;
        $quaParams->uid = $uid;
        $quaParams->rankId = $rankId;
        self::subscribeRegQuanUser($quaParams);
        $userInfo = $MiModel->where("id=$uid")->find();

        !empty($userInfo['fullName'])? '' : $data["fullName"] = $fullName;
        //LP 修改判断手机号是否重复
        $userCount = $MiModel->where("id!=$uid and phone=$phone")->count();
        if($userCount == 0){
            $userInfo['isVerifyPhone'] == 1 ? '' : $data["phone"] = $phone;
            $userInfo['isVerifyPhone'] == 1 ? '' : $data["isVerifyPhone"] = 1;
        }
        !empty($userInfo['wxNumber'])? '' : $data["wxNumber"] = $wxNumber;
        !empty($userInfo['email'])? '' : $data["email"] = $email;
        if(empty($userInfo['province'])){
            $data["city"] = $city;
            $data["province"] = $province;
            $data['county'] = '';
            $data['town'] = '';
            $data['rural'] = '';
        }
        if(strtotime($birthday)){
            $data["birthday"] = $birthday;
        }
        $data['customInfo'] = $customInfo;
        $sqlStr = '';
        foreach($data as $key=>$val){
            $sqlStr .= "`".$key."`='".$val."',";
        }
        $sqlStr = rtrim($sqlStr, ',');

        //$updateUserStatus = $MiModel->where("id=$uid")->save($data);
        $sql = "UPDATE `wx_".$cid."_user` SET ".$sqlStr." WHERE ( id=".$uid." )";

        $updateUserStatus = M()->execute($sql);
        if ($updateUserStatus === false) {
            Log::write('保存密友信息'.M()->getLastSql().'-cid-'.$cid);
            $MiModel->rollback();
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        /*好友对接第三方crm*/
        $miyouquanInfo = $myq_tab->where(['id'=>$qid])->find();
        if($miyouquanInfo['isSynchro'] && $miyouquanInfo['vid']){
            $arr = [];
            $arr[0]['uid'] = $uid;
            $arr[0]['qId'] = $qid;
            $bool = R('TaskQueue/addTaskQueue', [$name='synchroFriendsToCrm', $module='quan',
                $interfaceName='ApplePieAction/synchroFriends',$param=json_encode($arr),
                $execute_plan_time=date('Y-m-d H:i:s'), $flag=true, $isCycleExecute=0, $cycleTime=0]);
            if(!$bool){
                Log::write('jie保存同步好友任务失败-'.'uid-'.$uid.'-qid-'.$qid);
            }
        }
        //触发注册任务
        // $p=new StdClass();
        // $p->miUId=$uid;
        // $p->qId=$qId;
        // $p->key="REG";
        // Module::callModule("task", Session::$user,"updateTaskStatus", $p);
        $out = new StdClass();
        $out->code = 0;
        $out->qId = $qid;
        Output::instance()->object($out);
            
    }

    /**
     * [myRecommend 密友推荐]
     * @param  [type] $param [sId,uId,quanId,isComment为1则是推荐，为0则是取消推荐]
     * @return [type]        [result]
     */
    public function myRecommend($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $CommentModel = M("mirecomment");
        Session::switchCustomer($cid);

        $uId = Session::$user['uid'];
        $quanId = $param->quanId;
        $sId = $param->sId;
        $isComment = $param->isComment;
        $where['quanId'] = $quanId;
        $where['sId'] = $sId;
        $where['uId'] = $uId;
        $oldarr = $CommentModel->where($where)->find();
        if ($isComment && $isComment == 1) {
            if ($oldarr) {
                $data['deleted'] = 0;
                $result = $CommentModel->where($where)->save($data);
            } else {
                $data['deleted'] = 0;
                $data['uId'] = $uId;
                $data['sId'] = $sId;
                $data['quanId'] = $quanId;
                $data['createTime'] = date("Y-m-d H:i:s");
                $result = $CommentModel->where($where)->add($data);
            }
        } else {
            $data['deleted'] = 1;
            $result = $CommentModel->where($where)->save($data);
        }

        if ($result !== false) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function getActivitylistPage($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $qId = $param->qId;
        $uid = Session::$user['uid'];
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $MiQuanModel = M("quan_user");
        Session::switchCustomer($customerId);
        $result["qId"] = $qId;
        $result["fromUId"] = $uid;
        Output::instance()->module("quan", "quan_activity")->object($result);
    }

    public function getActivilyList($param)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $qId = $param->qId;
        $result["qId"] = $qId;
        $uId = Session::$user['uid'];
        $start = $param->start;
        $limit = $param->limit;
        Session::switchCustomer(0);
//        $vendorModel = M("quan_vendor");
        $miYouQuanModel = M("miyouquan");
        Session::switchCustomer($customerId);
        $order = "b.id desc";
        $pageStart = $start * $limit;
        $where["a.id"] = array('eq', $qId);
        $where["b.deleted"] = array('eq', 0);
        $where["b.status"] = array('eq', 1);
        $where["a.deleted"] = array('eq', 0);
        $where["b.type"] = array('eq', "love");
        $list = $miYouQuanModel->alias("a")
            ->join("inner join wx_miactivity b on a.vid=b.vId")
//            ->join("INNER JOIN wx_miyouquan c ON c.id=a.quanId")
            ->join("INNER JOIN (SELECT * FROM wx_mishare WHERE module='miactivity') AS d ON d.moduleId=b.id ")
            ->field("d.id as sId,b.*")
            ->where($where)
            ->order($order)
            ->limit($pageStart, $limit)
            ->select();

        $count = $miYouQuanModel->alias("a")
            ->join("inner join wx_miactivity b on a.vid=b.vId")
//            ->join("INNER JOIN wx_miyouquan c ON c.id=a.id")
            ->join("INNER JOIN (SELECT * FROM wx_mishare WHERE module='miactivity') AS d ON d.moduleId=b.id ")
            ->where($where)
            ->order($order)
            ->count();

        $proList = new StdClass();
        $proList->count = $count;
        $proList->pageCount = getPageCount($count, $limit);
        if ($list) {
            $proList->list = $list;
        } else {
            $proList->list = array();
        }
        $result["proList"] = $proList;
        Output::instance()->object($result);
    }


    /**
     * 营销圈进入首页前逻辑判断
     */
    public function judgeUserStatus($param)
    {
        Log::write('regQuanSave-param:'.serialize($param));
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
//		self::checkMUserAuth($param);
        $qId = $param->qId;
        $uid = Session::$user['userId'];
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        Session::switchCustomer(0);
        $quanModel = M("quan_user");
        $miquanModel = M("miyouquan");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $userModel = M("user");
        $where["qid"] = array('eq', $qId);
        $where["uid"] = array('eq', $uid);
        $where["deleted"] = array('eq', 0);
        $result = $quanModel->where($where)->find();
        $quanInfo = $miquanModel->where("id=$qId")->find();
        $userList = $userModel->where("id=$uid")->find();
        if (!$result && $qId) {
            //此时用户不在这个圈里面
            $joinresult = $quanModel->alias("a")
                ->join("inner join wx_miyouquan b on a.qid = b.id")
                ->where("a.uid=$uid and b.cId=$customerId and a.deleted=0 and a.status=1 and a.qid<>$qId")
                ->find();
            if ($joinresult) {
                Output::instance()->resultCode(1, '已存在另外一个圈中');
                return;
            }
            //开启了自动加入
            if ($quanInfo['staffJoin']) {
                $cusWhere["agent"] = array("eq", "service");
                $cusWhere["customerId"] = array("eq", $customerId);
                $cusWhere["openid"] = array("eq", $userName);
                $staffInfo = $customerUser->where($cusWhere)->find();
                if ($staffInfo) {
                    $quaParams = new stdClass();
                    $quaParams->userName = $userName;
                    $quaParams->id = $qId;
                    $quaParams->statis = $param->statis;
                    $quanInfo['signSaleSource'] ? $quaParams->signSaleSource = 1 : "";
                    self::subscribeRegQuanUser($quaParams);
                    Output::instance()->resultCode(0, '跳转到营销圈首页');
                    return;
                }
            }
            if ($quanInfo["registerStatus"] == 1) {
                if ($quanInfo["joinContent"]) {
                    $miInfo = $miquanModel->alias("a")
                        ->join("inner join wx_module_product b on a.joinPid=b.id")
                        ->field("b.fromCustomerId")
                        ->where("a.id=$qId")->find();
                    Output::instance()->resultCode(2, '跳转到购买说明页');
                    return;
                }
                Output::instance()->resultCode(4, '跳转到注册页');
                return;
            } else if ($quanInfo["joinType"] == 1) {
                $quaParams = new stdClass();
                $quaParams->userName = $userName;
                $quaParams->id = $qId;
                $quaParams->miUId = $param->miUId;
                self::subscribeRegQuanUser($quaParams);
                $param->examine = 1;
                Output::instance()->resultCode(4, '跳转到需要审核的注册页');
                return;
            } else {
                $quaParams = new stdClass();
                $quaParams->userName = $userName;
                $quaParams->id = $qId;
                $quaParams->miUId = $param->miUId;
                self::subscribeRegQuanUser($quaParams);
                Output::instance()->resultCode(0, '跳转到营销圈首页');
                return;
            }
        } else if ($qId && !$result["status"]) {
            $param->examine = 1;
            Output::instance()->resultCode(5, '审核中状态');
            return;
        } else {
            Output::instance()->resultCode(0, '跳转到营销圈首页');
            return;
        }
        $condition["a.qid"] = array('eq', $qId);
        $condition["a.uid"] = array('eq', $uid);
        $result = $quanModel->alias("a")
            ->join("inner join wx_miyouquan b on a.qid=b.id")
            ->where($condition)->find();
        $result["qId"] = $qId;
        $param->page = "shopIndex";
        $sId = self::addShare($param);
        //添加分享相关
        $fromUId = $param->fromUId;
        if ($fromUId) {
            $uid = $fromUId;
            $result["isShare"] = 1;
        }
        $result["sId"] = $sId;
        $result["fromUId"] = $uid;
        $community = $param->community;
        if ($community) {
            $params = new StdClass();
            $params->qid = $qId;
            Module::callModule("community", NULL, 'index', $params);
        } else {
            Output::instance()->module('quan', "quanUserIndex")->object($result);
        }
    }

    //购买介绍页面
    /**
     * 进入注册页
     * @param $param /
     */
	public function payContentDetail($param){
        $token=$param->token;
        $token = Module::callModule("personCenter",null,"verifyToken",$token);
		$uid = Session::$user['userId'];
		$qId=$param->qId;
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MiQuanModel=M("miyouquan");
		$mimall = M("mimall_user");
		$moduleProduct = M("module_product");
		Session::switchCustomer($customerId);
        $registerDataModel = D('QuanRegisterData', 'Model');
        $user_tab = M('user');
		$miInfo=$MiQuanModel->alias("a")
			->join("left join wx_module_product b on a.joinPid=b.id")
			->join("left join wx_mishare c on b.id=c.moduleId and c.module='product'")
			->field("a.*,c.id as sId,b.vId,b.fromCustomerId,b.distributionId,b.proSource")
			->where("a.id=$qId")
			->find();
		if ($miInfo['joinPid']){
			$productInfo=$moduleProduct->where("id=".$miInfo['joinPid'])->find();
		}else{
			$productInfo=[];
		}
		//<侯佳2018-07-17添加，组织注册项配置>
		if ($miInfo['config']) {
		    $arrConfig = json_decode($miInfo['config'], true);
		    $regPro = $arrConfig['regPage']['regPro'];
		    $registerDatas = [];
		    foreach ($regPro as $value) {
                $registerData = $registerDataModel->getRegisterData(['id' => $value['type']]);
                array_push($registerDatas, $registerData);
            }
        }
        $miInfo['registerDatas'] = $registerDatas;
        //</侯佳2018-07-17添加，组织注册项配置>
		if($miInfo["joinContent"]){
			$miInfo["joinContent"]=json_decode($miInfo["joinContent"],true);
		}
		if(self::joinQualifications($qId)){
			$miInfo['satisfy'] = 1;
		}else{
			$miInfo['satisfy'] = 0;
		}
        /*注册是带入历史信息jie*/
        $userInfo = $user_tab->where(['id'=>$uid])->field('fullName,phone,email,city,province,birthday,wxNumber,address,isVerifyPhone')->find();
		$miInfo["userInfo"]=$userInfo;
		$miInfo["qId"]=$qId;
		$miInfo["uid"]=$uid;
		$miInfo["miUId"]=$param->miUId;
		$planCustomerId=C("PLANT_CUSTOMERID");
		$miInfo['planCustomerId'] = $planCustomerId;
		$miInfo['productInfo'] = $productInfo;
		Output::instance()->object($miInfo);
	}
    /**
     * 获取平台提现设置信息
     */
    public function withdrawConfig($qid){
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $cuSettingModel=M("customer_setting");
        $quanModel=M("quan_user");
        Session::switchCustomer($customerId);
        $userModel = M('user');

        //获取提现的设置信息
        $withdrawConfig = $cuSettingModel->where(['cid' => $customerId])->getField('withdrawConfig');
        $return['withdrawConfig'] = json_decode($withdrawConfig, true);

        //判断是否可以提现到银行卡，可以则获取银行卡信息
        $bankAccount = $userModel->where(['id' => $userId])->getField('bankAccount');
        $bankAccount = json_decode($bankAccount,true);
        $return['bankAccount'] = $bankAccount['withdraw'];


        //判断当前是否可以提现
        if($return['withdrawConfig']['timeType'] == 1) {
            $nowDate = date('d');
            if (($return['withdrawConfig']['startTime'] <= $nowDate) && ($nowDate <= $return['withdrawConfig']['endTime'])){
                $return['isWithdraw'] = 1;
            }else{
                $return['isWithdraw'] = 0;
            }
        }else{
            $return['isWithdraw'] = 1;
        }
        $miCoins = $quanModel->where("qid = $qid and uid = $userId and deleted = 0")->field('ROUND(miCoins,2) as miCoins')->find();
        $return['miCoins'] = $miCoins['miCoins'];
        Output::instance()->object($return);
    }
    /**
     * 添加银行卡
     * @param $bankAccountName  银行名称
     * @param $bankCardNum      银行账户卡号
     * @param $bankCardName     银行账户名
     */
    public function addUserBankAccount($bankAccountName,$bankCardNum,$bankCardName,$bankWxNum,$bankPicUrl){
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        $userModel = M('user');
        $userBankInfo[0]['bankAccountName']=$bankAccountName;
        $userBankInfo[0]['bankCardNum']=$bankCardNum;
        $userBankInfo[0]['bankCardName']=$bankCardName;
        $userBankInfo[0]['bankPicUrl']=$bankPicUrl;
        $userBankInfo[0]['bankWxNum']=$bankWxNum;

        //取出原银行卡信息
        $bankAccount = $userModel->where(['id' => $userId])->getField('bankAccount');
        if(!empty($bankAccount)){
            $bankAccount = json_decode($bankAccount,true);
            $userBankInfo= array_merge($bankAccount['withdraw'],$userBankInfo);
        }
        $bankAccount['withdraw'] = $userBankInfo;
        $bankAccount = json_encode($bankAccount);

        //信息入库
        $result = $userModel->where(['id' => $userId])->setField('bankAccount', $bankAccount);
        if(is_numeric($result)){
            $return['code'] = 0;
            $return['msg'] = 'ok';
            Output::instance()->object($return);
        }else{
            $return['code'] = 0;
            $return['msg'] = 'fail';
            Output::instance()->object($return);
        }

    }
    /**
     * 删除银行卡
     * @param $bankAccountName  银行名称
     * @param $bankCardNum      银行账户卡号
     * @param $bankCardName     银行账户名
     */
    public function deleteUserBankAccount($index){
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['userId'];
        $userModel = M('user');

        //取出原银行卡信息
        $bankAccount = $userModel->where(['id' => $userId])->getField('bankAccount');
        $bankAccount = json_decode($bankAccount,true);
         unset($bankAccount['withdraw'][$index]);
        $userBankInfo = json_encode($bankAccount);

        //信息入库
        $result = $userModel->where(['id' => $userId])->setField('bankAccount', $userBankInfo);
        if(is_numeric($result)){
            $return['code'] = 0;
            $return['msg'] = 'ok';
            Output::instance()->object($return);
        }else{
            $return['code'] = 0;
            $return['msg'] = 'fail';
            Output::instance()->object($return);
        }

    }

    /**
     * 微信支持转账的银行列表
     */
    public function wxPayBankList(){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $wxBankModel=M("weixin_pay_bank");
        Session::switchCustomer($customerId);

        $arr = $wxBankModel->select();
        $return['code'] = 0;
        $return['msg'] = 'ok';
        $return['data'] = $arr;
        Output::instance()->object($return);

    }

    public function whiteListJudge($qid,$phone = NULL){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $miyouquanModel=M("miyouquan");
        $whiteListModel=M("rank_white_list");
        $productModel=M("module_product");
        Session::switchCustomer($customerId);
        $quanInfo = $miyouquanModel->where(['id' => $qid])->find();
        $joinPid = json_decode($quanInfo['joinPid'], true);
        $rankId = array_column($joinPid, 'rankId');
        foreach($rankId as $k=>$v){
            if (empty($v)) {
                unset($rankId[$k]);
            }
        }
        $rankId = implode(',',$rankId);
        $where['rankId'] = array('in', $rankId);
        $where['phone'] = array('eq', $phone);
        $where['status'] = array('eq', 0);
        $phoneWhiteList = $whiteListModel->where($where)->find();
        if($phone && !empty($phoneWhiteList)){
            foreach ($joinPid as $key=>$value){
                if($value['rankId'] == $phoneWhiteList['rankId']){
                    $pid = $value['pid'];
                }
            }
            $proInfo = $productModel->alias('a')->where(['a.id' => $pid])->join("wx_mishare as b on a.id = b.moduleId and b.module = 'product'")->field('a.id as pid,b.id as sId,a.name as proName,a.fixedPrice as price,a.vId')->find();
            $phoneWhiteList = array_merge($phoneWhiteList,$proInfo);
            $return['code'] = 0;
            $return['msg'] = '已匹配到白名单';
            $return['data'][0] = $phoneWhiteList;
            Output::instance()->object($return);
            return;
        }
        foreach ($joinPid as $key=>$value){
            $proInfo = $productModel->alias('a')->where(['a.id' => $value['pid']])->field('a.name,a.fixedPrice as price,b.id as sId,a.vId')->join("wx_mishare as b on a.id = b.moduleId and b.module = 'product'")->find();
            $joinPid[$key]['price'] = $proInfo['price'];
            $joinPid[$key]['proName'] = $proInfo['name'];
            $joinPid[$key]['sId'] = $proInfo['sId'];
            $joinPid[$key]['vId'] = $proInfo['vId'];
        }
        if($quanInfo['isShowRank'] == 1){
            $return['code'] = 1;
            $return['msg'] = '获取购买列表成功';
            $return['data'] = $joinPid;
            Output::instance()->object($return);
            return;
        }
        $data[0] = $joinPid[0];
        $return['code'] = 2;
        $return['msg'] = '获取默认购买商品成功';
        $return['data'] = $joinPid;
        Output::instance()->object($return);
        return;
    }






}
